Optimization Techniques of NGINX+PHP-FPM

Source: Internet
Author: User
Tags unix domain socket cpu usage high cpu usage
This article mainly introduces the nginx+php-fpm of the optimization skills, has a certain reference value, now share to everyone, the need for friends can refer to

Summary of NGINX+PHP-FPM optimization techniques

here is a piece of article found from the Internet, serious practice once again, there are a lot of reference to the place can learn, because the previous article typesetting is very confusing, so I study while adding to write this article, all copyright belongs to the original author all

UNIX Domain Socket Communication

This communication method is briefly described before Unix Domain Socket , see: Nginx+PHP-FPM Domain Socket Configuration method
UnixDomain Socket Because the network does not go, it can improve Nginx and php-fpm communication performance, but in high concurrency will be unstable.

NginxWill frequently error:

Connect () to Unix:/dev/shm/php-fcgi.sock failed (11:resource temporarily unavailable) while connecting to upstream

Stability can be improved in the following two ways:

1. Adjust nginx the height and php-fpm the backlog
The configuration method is: In the nginx configuration file under this domain name server , listen 80 added later default backlog=1024 .
php-fpm.confin the same configuration listen.backlog 1024 , the default is 128 .
2. Increase the sock php-fpm number of files and instances and then create a new file in which the request is sock Nginx upstream load balanced to two sock files through the module
Behind the two sets of php-fpm examples.

PHP-FPM parameter Tuning

2.1 Number of processes

# PHP-FPM Initial/idle/MAX worker processes Pm.max_children = Pm.start_servers = Pm.min_spare_servers = 5 Pm.max_spare_servers = 35

2.2 Maximum number of processing requests

The maximum number of processing requests is when a php-fpm worker process terminates after processing the number of requests, and the master process restarts respawn a new one.
The primary purpose of this configuration is to avoid php memory leaks caused by third-party libraries referenced by the Interpreter or program

Pm.max_requests = 10240

2.3 Maximum Execution time

The maximum execution time php.ini php-fpm.conf can be configured in and, and the configuration items are respectively max_execution_time request_terminate_timeout .
Its effects and effects see: 502 and 504 errors in Nginx

How to troubleshoot high CPU usage in PHP-FPM

1. CPU Usage Monitoring method

Top command:
After executing top the command directly, enter 1 to see the usage of each core CPU . And the top -d 0.1 sampling time can be shortened by this.
The bottom sar looks like a minimum of 1 seconds.

SAR command:

# SAR and iostat command installation: Sysstat.x86_64:The SAR and iostat system monitoring commands yum install-y sysstat.x86_64 # Execute Sar-p All 1 100. -P all indicates that all cores are monitored, 1 means every 1 seconds, and 100 means acquisition 100 times. # output results are as follows: CPU%user%nice%system%iowait%steal%idleall 85.54 0.00 5.69 0.00 0      .00 8.76 0 74.75 0.00 25.25 0.00 0.00 0.00 1 98.00 0.00 2.00 0.00 0.00 0.00 2 89.22 0.00 3.92 0.00 0.00 6.86 3 91.00 0.00 2.00 0.0      0 0.00 7.00 4 75.00 0.00 9.00 0.00 0.00 16.00 5 94.95 0.00 5.05      0.00 0.00 0.00 6 95.00 0.00 4.00 0.00 0.00 1.00 7 87.88 0.00 4.04 0.00 0.00 8.08 8 93.94 0.00 3.03 0.00 0.00 3.03 9 88.00 0.00 3 .00 0.00 0.00 9.00 10 89.11 0.00 2.97 0.00 0.00 7.92 11     82.35 0.00 3.92 0.00 0.00 13.73 12 73.27 0.00 7.92 0.00 0.00 18.8     1 13 81.44 0.00 4.12 0.00 0.00 14.43 14 77.23 0.00 6.93 0.00 0.00 15.84 15 78.79 0.00 4.04 0.00 0.00 17.17

2. Turn on slow log

Configure php-fpm the output slow log with a threshold of 2 seconds:

Request_slowlog_timeout = 2slowlog = log/$pool. Log.slow

Analyze summary php-fpm Slow logs with the Sort/uniq command:

[Root@boole log] grep-v "^$" www.log.slow.tmp | Cut-d ""-F 3,2 | Sort | uniq-c | SORT-K1,1NR | Head-n 5181 Run ()/www/test.net/framework/web/filters/cfilter.php:41 5156 filter ()/www/test.net/framework/web/fil ters/cfilterchain.php:131 2670 =/www/test.net/index.php 2636 run ()/www/test.net/application/controllers/survey/ index.php:665 2630 Action ()/www/test.net/application/controllers/survey/index.php:18 2625 run ()/www/test.net/ framework/web/actions/caction.php:75 2605 runwithparams ()/www/test.net/framework/web/ccontroller.php:309 2604 Runaction ()/www/test.net/framework/web/filters/cfilterchain.php:134 2538 run ()/www/test.net/framework/web/ ccontroller.php:292 2484 runactionwithfilters ()/www/test.net/framework/web/ccontroller.php:266 2251 run ()/www/test . net/framework/web/cwebapplication.php:276 1799 Translate ()/www/test.net/application/libraries/limesurvey_ lang.php:118 1786 Load_tables ()/www/test.net/application/third_party/php-gettext/gettext. php:254 1447 Runcontroller ()/www/test.net/framework/web/cwebapplication.php:135 # parameter explanation: Sort: Sorting Words uniq-c : Displays unique rows and the number of occurrences of the line at the beginning of each row sort-k1,1nr: sorted by the first field, numerically, and in reverse head-10: Take the first 10 rows of data

3. Track processes with Strace

1. The utilization nohup will be performed in the strace background until attach the process on it php-fpm dies:

Nohup strace-t-P 13167 > 13167-strace.log parameter Description:-C counts the time, frequency, and number of errors that are performed by each system call.-D output strace debug information about standard errors.-F Trace by fork Invokes the resulting child process.-o filename, then the trace results of all processes are output to the corresponding filename-f attempt to trace Vfork calls. At-F, vfork is not tracked.-h outputs a brief help message.-I output the entry pointer to the system call.-Q Suppresses the output of messages about secession.-R prints out relative time about, each system called.-T adds time information to each line in the output. The-TT is preceded by the time information in each line of the output, in microseconds.-ttt microsecond output in seconds.-T displays the elapsed time for each call.-V Output all system calls. Some calls about environment variables, states, input and output, etc. are not output by default because they are used frequently.-V outputs the version information of the Strace.-X outputs non-standard strings in 16 binary-xx all strings are output in 16 binary form. Column sets the output location of the return value. The default is 40.-e Execve records only EXECVE such systems call-p main process number

2. Can also use -c the use of parameters to strace help summarize, very convenient very powerful!

[root@b28-12 log]# strace-cp 9907Process 9907 attached-interrupt to quitprocess 9907 detached% time seconds usecs/           Call calls errors syscall--------------------------------------------------------------56.61 0.016612       5 3121 read11.11 0.003259 1 2517 715 stat 8.04 0.002358 7           349 BRK 6.02 0.001767 1 1315 poll 4.28 0.001255 6 228  Recvfrom 2.71 0.000796 1 671 Open 2.54 0.000745 0 2453 Fcntl 2.37 0.000696 1 1141 Write 1.69 0.000497 1 593 Access 1.37 0           .000403 0 1816 Lseek 0.89 0.000262 1 451 sendto 0.56 0.000163           1 276 208 Lstat 0.49 0.000145 0 384 getcwd 0.31 0.000090 0 1222 FSTat 0.28 0.000082 0 173 munmap 0.26 0.000077 0 174 mmap 0.24 0.000069 2 Socket 0.23 0.000068 0 725 Close 0.00 0.0000    0 rt_sigaction 0.00 0.000000 0 Rt_sigprocmask 0.00    0.000000 0 1 Rt_sigreturn 0.00 0.000000 0 0.00 Setitimer 0.000000 0 Connect 0.00 0.000000 0 2 Accept 0.00 0.0000           0 recvmsg 0.00 0.000000 0 Shutdown 0.00 0.000000           0 bind 0.00 0.000000 0 getsockname 0.00 0.000000           0 setsockopt 0.00 0.000000 0 getsockopt 0.00 0.000000          0 8 Getdents 0.00 0.000000 0 chdir 0.00 0.000000 0 1 futex-  -------------------------------------------------------------100.00 0.029344 18000 986 Total

4. Accelerating PHP Interpretation execution

If your own program does not have a problem, just do too much work, can not be optimized. Consider using APC or xcache waiting for PHP accelerators to reduce CPU php the time-consuming of interpreting files.
These PHP accelerators php generate intermediate code when the file is first interpreted opcode , so the subsequent execution is much faster and some operations are reduced CPU . In the following xcache example,
See how to install and configure.

xcachethe installation command is as follows, ./configure the parameters of many do not know what to do with, the official website does not specify, so only opened --enable-xcache :

Tar zxvf xcache-3.0.3.tar.gz     /usr/local/php/bin/phpize     ./configure--with-php-config=/usr/local/php/bin /php-config--enable-xcache make do     install

php.iniIn the configuration below, the most important is the red two parameters, the general recommendation xcache.size depends on the number of php files, xcache.count and the CPU same number of cores:

[Xcache.admin]xcache.admin.enable_auth = Offxcache.admin.user = "XCache" Xcache.admin.pass = "" [Xcache]xcache.shm_ Scheme = "Mmap" Xcache.size=1024mxcache.count =16xcache.slots =8kxcache.ttl=0xcache.gc_interval =0xcache.var_size= 16mxcache.var_count =1xcache.var_slots =8kxcache.var_ttl=0xcache.var_maxttl=0xcache.var_gc_interval = 300xcache.test =offxcache.readonly_protection = off;xcache.readonly_protection = Onxcache.mmap_path = "/dev/zero"; Xcache.mmap_path = "/tmp/xcache" xcache.coredump_directory = "" Xcache.cacher =onxcache.stat=onxcache.optimizer =Off [ Xcache.coverager];; Xcache.coverager =on; Xcache.coveragedump_directory = ""

Frequently asked questions are php-fpm errors when you start:

Cannot open or create file set by Xcache.mmap_path, check the path permission or check xcache.size/var_size against system Limitation

This is because it /tmp/xcache is a file and cannot be created as a directory.

After restarting the php-fpm service, top you can see with the command that each worker process VIRT (including the swap extents) is xcache.size size, but REQ becomes very small.
Use the above configuration to CPU shorten the peak time of usage, but all cores will reach above at peak 90% , not knowing where there is no configuration.
In addition to high concurrency, /dev/zero This configuration often results in Nginx 502 errors. /tmp/xcacheand open it is readonly_protection very stable.

PHP Program Performance Monitoring

The common method is to turn xdebug on the performance monitoring function, the Xdebug output results through the WinCacheGrind software analysis.
xdebugInstallation and debugging with the IDE see: Vim+xdebug Debugging PHP

The items configured in the php.ini are output performance information:

Xdebug.auto_trace = Onxdebug.auto_profile = Onxdebug.collect_params = Onxdebug.collect_return = Onxdebug.profiler_ Enable = Onxdebug.trace_output_dir = "/tmp" XDEBUG.PROFILER_OUTPUT_DIR = "/tmp"

This xdebug will output all performance data that executes the PHP function, but the resulting file will be larger. You can turn off some options such as Collect_params, Collect_return,
To reduce the amount of data output. Or turn off automatic output to monitor the specified function by calling the Xdebug function at the end of the function that you want to monitor.

The output filename is similar cachegrind.out.1277560600 and trace.3495983249.txt can be Windows used WinCacheGrind for graphical analysis under the platform.
WinCacheGrindHow to use the online there are many introductions, this is not explained in detail, Wincachegrind for GitHub

Conclusion

The above are php some of the recent procedures to optimize the work summarized some optimization methods, for each location of the configuration please read the official documents to modify, do not have to be based on this document, this document only describes the method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.