Nginx_ Notes Sharing _php-fpm detailed

Source: Internet
Author: User
Tags php source code sapi

Reference

Http://syre.blogbus.com/logs/20092011.html
http://www.mike.org.cn/articles/what-is-cgi-fastcgi-php-fpm-spawn-fcgi/
Http://www.larro.cn/?p=35


Nginx PHP php-fpm CGI fastcgi and so on the relationship between them confusing, Google found a day a lot of good articles introduced, but are all said to let people crazy, hereby will be the above several predecessors of the article re-organized a bit, in the spirit of Take doctrine Thought (Khan), Copy the original author part of the article, and added their own ideas, clear a lot of ideas, again thank the predecessors selfless dedication!!



Why should Nginx use fastcgi to parse PHP


In general, there are three ways that Web server supports PHP:
Implemented through Web server built-in modules, such as Apache's mod_php module, but Nginx does not have this module.
The disadvantage of this approach through CGI is poor performance, because each time the server encounters these scripts it is necessary to restart the script parser to execute the script and then return the results to the server, on the other hand it is not very secure;
FASTCGI,FASTCGI is the improvement of CGI, the general use of C/s structure, the general script processor will start one or more daemon processes, each time Nginx encountered PHP script, the direct delivery to the FastCGI process to execute, The resulting results are then returned to the browser.



What is CGI


The full name is a "public Gateway Interface" (Common Gateway Interface), a tool that Web server "chats" with programs on your or other machines, and its programs must run on the Web server.
CGI can be written in any language, as long as the language has standard input, output, and environment variables, such as PHP,PERL,TCL.


What is FastCGI



FastCGI is a scalable, high-speed interface for communication between Web servers and scripting languages.
FastCGI is supported by many scripting languages, including PHP, if compiled with the--enable-fastcgi option.
Most popular Web servers support FastCGI, including Apache (mod_fastcgi and Mod_fcgid), Zeus,nginx, and lighttpd.
The main advantage of FastCGI is that it separates dynamic language from Web server. This technology allows Web servers and dynamic languages to run on different hosts. This can improve scalability and security without significant efficiency losses.


php-fpm can be used with any Web server that supports external FastCGI technologies (such as Nginx).

Give me an example.
For example, I have a lnmp (nginx mysql PHP) server load is very high, and now has three servers, the original LNMP is now split into three servers, according to the application is divided into two parts, of course, there is no consideration of costs, but in the context of the combination of virtualization technology, The benefits of split by application are very large, in addition to being able to give the web, db to do load balancing and high availability is not one day our php-fpm can also lb with ha?


WWW1 Web Server NGINX
PHP1 php_script server PHP (PHP-FPM)
DB1 MySQL server MySQL

PHP-FPM, spawn-fcgi php-cgi are fastcgi managers.


What is php-cgi


PHP-CGI is the fastcgi manager that comes with PHP.
To start php-cgi, use the following command:
Php-cgi-b 127.0.0.1:9000
Php-cgi of the poor
1, php-cgi change php.ini configuration need to restart php-cgi to let the new Php-ini take effect, can not smooth restart
2, directly kill the php-cgi process, PHP can not run. (PHP-FPM and spawn-fcgi do not have this problem, the daemon will smooth the new child process from the newly generated.) )



What is spawn-fcgi


SPAWN-FCGI is a general-purpose fastcgi Management Server , it is a part of LIGHTTPD, many people use lighttpd spawn-fcgi for fastcgi mode management work, but there are many shortcomings. And the php-fpm of how much to alleviate some of the problems, but PHP-FPM has a drawback is to recompile, which for some already running environment may have a small risk (refer), but in PHP 5.3.* can be directly used php-fpm.
SPAWN-FCGI has now become a single project, more stable, but also to many Web site configuration to facilitate. There are a number of sites to match it with Nginx to solve dynamic Web pages.



What is PHP-FPM


PHP-FPM is actually a patch of PHP source code, designed to integrate fastcgi process management into the PHP package, it must be patched into your PHP source code, after compiling and installing PHP can be used.
Php5.3.* has been integrated PHP-FPM, is no longer a third-party package, PHP-FPM provides a better way to manage the PHP process, can effectively control memory and process, can be smooth overloaded PHP configuration, more advantages than spawn-fcgi, so the official PHP is included in the The php-fpmcan be turned on with the--ENABLE-FPM parameter when/configure.

The following is a list of the issues that are related to enabling FastCGI SAPI and how php-fpm resolves their comparisons.

Description PHP comes with a spawn-fcgi + spawn-php.sh + daemontools PHP-FPM
PHP Daemon: PID file, log file, Setsid (), setuid (), Setgid (), chroot () (-) (+) (+)
Process Management. You can use "graceful" to stop and start the PHP worker process without losing the request. The ability to smoothly upgrade the configuration and binaries without losing any requests. PHP4 (-), php5 (only graceful) (-) (+)
The IP address of the Web server that strictly restricts the source request PHP4 (-) php5 (+) (starting from 5.2.2) (-) (+)
Dynamically adjust the number of processes based on load (-) (-) Todo
Start the Worder process with different uid/gid/chroot/environment and different php.ini options. You don't need safe mode! (-) (-) (+)
Logging worker processes stdout and stderr logs (-) (-) (+)
If the optimizer is used, an emergency restart of all processes in case of accidental corruption of shared memory (-) (-) (+)
If Set_time_limit () fails, ensure that the process ends (-) (-) (+)
Featured function Error header, optimized upload support, fastcgi_finish_request ()


At this point I have understood the relationship between them!!!

The following is a further introduction of PHP-FPM!!


Featured Features
All of these features are implemented in a "no-break" manner. That is, if you do not use them, their presence does not affect the functionality of PHP-they are all "transparent".
Error Header
Range: php.ini options
Category: Convenience
By default, if the PHP script being accessed contains a syntax error, the user receives an empty "OK" page. This is not convenient. Error header This php.ini option allows an HTTP error code to be generated in this case, such as "http/1.0 550 server made Big Boo", which interrupts the Web Server request and displays a correct error page.
If you want to implement such a feature, you need to add a fastcgi.error_header = "http/1.0 550 Server made Big Boo" in php.ini
A similar, but not identical, feature was added to php-5.2.4: If the php script being accessed contains a syntax error and display_errors = off, it returns "http/1.0 Internal Server Error" immediately.
If you need to set a 503 error, or want to make this behavior independent of the display_errors settings, then you can use Fastcgi.error_header. If you enable PHP-FPM on php-5.2.5 or above, the fastcgi.error_header has a higher priority.
Optimized upload support
Essence: Web Server support
Type: Optimization
This feature, like the name, speeds up processing of large POST requests, including file uploads. Optimization is achieved by writing the request body to a temporary file, and then passing the file name to the FASTCGI protocol instead of the request body. As far as I know, only nginx0.5.9 and above support this function. Obviously, this mode is only available when PHP and Web server are on a single machine.
Nginx Sample configuration:
Location ~ \.php$ {
Fastcgi_pass_request_body off;
Client_body_in_file_only clean;
Fastcgi_param request_body_file $request _body_file;
...
Fastcgi_pass ...;
}
There is no need to configure anything in PHP. If PHP receives the parameter request_body_file, it reads the request body, and if not, reads the request body from the FASTCGI protocol itself.
In combination with this feature, you can consider using a memory file system for temporary files, such as TMPFS (Linux):
Client_body_temp_path/dev/shm/client_body_temp;
Fastcgi_finish_request ()
Scope: PHP functions
Type: Optimization
This feature can improve the processing speed of some PHP requests. If some processing can be done after the page has been generated, you can use this optimization. For example, saving a session in Memcached can be done after the page is handed over to the Web server. Fastcgi_finisth_request (), which can end the response output, the Web server can immediately start handing over to the impatient client, and at this point, PHP can handle many things in the context of the request. For example, save session, convert uploaded videos, handle statistics, and so on.
Fastcgi_finisth_request () will trigger the shutdown function to run.
Request_slowlog_timeout
Range: php-fpm.conf options
Category: Convenient
This option allows you to track the execution of slow scripts and log them together with the call stack. For example, the following settings:
<value name= "Request_slowlog_timeout" >5s</value>
<value name= "Slowlog" >logs/slow.log</value>
The recorded slow.log may look like this:
SEP 16:22:19.399162 pid 29715 (pool default)
Script_filename =/local/www/stable/www/catalogue.php
[0x00007fff23618120] mysql_query ()/srv/stable/common/database/class. Mysqlrequest.php:20
[0x00007fff23618560] GetResult ()/srv/stable/common/database/class. facade.php:106
[0x00007fff23618aa0] Query ()/srv/stable/common/mysite.com/orm/class.usersmapper.php:99
[0x00007fff23618d60] Resolvebyid ()/srv/stable/common/mysite.com/orm/class.user.php:629
[0x00007fff236193b0] GetData ()/srv/stable/common/class. Dataentity.php:90
[0x00007fff236195d0] Load ()/srv/stable/common/mysite.com/orm/class.user.php:587
[0x00007fff23619a00] Getishidden ()/srv/stable/common/mysite.com/class.user.php:42
[0x00007fff2361a470] GetName ()/local/www/stable/www/catalogue.php:41
At the same time, the following records are saved in Error.log:
Sep 16:22:19.399031 [WARNING] fpm_request_check_timed_out (), line 135:child 29715, script '/local/www/stable/www/ Catalogue.php ' (pool default) executing too slow (5.018002 sec), logging
As you can see in the example, the script runs for more than 5 seconds and is likely due to a slow MySQL response (top backtrace).
FAQs
Can q:php-fpm be used with zendoptimize?
A: It's perfectly possible.

Can q:php-fpm be used with optimizations such as Zendplatform, XCache, Eaccelerator, APC, etc.?
A: Yes. The PHP-FPM architecture and any kind of shared memory for high-speed opcode caching are applicable. The only limitation is that all worker processes can only be used for one cache, even if they run with different uid/gid
Q: Why do I have to patch PHP? SPAWN-FCGI don't need this!
A:PHP-FPM is created to enhance ease of management. PHP that has not been patched does not:
Smooth restart PHP without losing requests, including upgrading PHP binaries and/or extensions.
Running worker processes with different uid/gid/chroot environments
All settings have only one configuration file
Based on load dynamic request (TODO)
Real-time statistical performance for PHP requests (TODO)
Q: Why run php-fpm with root? Is it safe?
A: Starting php-fpm with Root is only meaningful if you plan to use different uid/gid PHP to handle requests. For example, in a shared host on the different sites, because only when the master process with root run, can establish a different uid/gid sub-process, which is quite safe, the master process itself never to handle the request, in any case, PHP-FPM will not use root Identity to process the request.

Can q:php-fpm speed up php script processing?
A: No, it doesn't affect the processing speed, but if you use some special features, you can have a performance boost for some specific requests.

Q: If I move my site from mod_php to PHP-FPM, will I get a performance boost?
A: Generally, when there is a large amount of free memory available on the server, the performance gains from migrating to PHP-FPM may not be significant, but if the memory is not plentiful, the performance gain is considerable, and in some cases 300-500% can be achieved. This may be due to the fact that Nginx + PHP-FPM generally use less memory than Apache + mod_php. And the VFS cache works more efficiently due to more free memory.

Will Q:PHP-FPM be included in the official PHP in the future?
A: I hope so. Currently, the PHP-FPM code protocol is the GPL. So now the PHP-FPM code does not match the PHP protocol (like BSD). This is a temporary measure. This option is intended to simplify the development process. Once the code is fully functional, such as adaptive generation of sub-processes and other things, the protocol will be changed to match. After that, PHP-FPM is officially released to the PHP development team and is recommended for inclusion.
Mailing list
If you have any questions, please do not hesitate to write an email in the mail group.
English:highload-php-en Russian:highload-php-ru
Document
PHP-FPM has been tested on Linux, MacOSX, Solaris, and FreeBSD.
Be sure that libxml2 (called Libxml2-devel on some systems) is already installed.
Download the smallest PHP and PHP-FPM
$ BZIP2-CD php-5.2.5.tar.bz2 | Tar XF-
$ GZIP-CD php-5.2.5-fpm-0.5.7.diff.gz | Patch-d PHP-5.2.5-P1
$ cd php-5.2.5 &&./configure--enable-fastcgi--ENABLE-FPM
$ make all Install
Edit $prefix/etc/php-fpm.conf
Run $prefix/bin/php-cgi--fpm
Double check $prefix/logs/php-fpm.log
Run Phpinfo () to check if your site is still working
The PID of the master process is stored in the $prefix/logs/php-fpm.pid
The master process can understand the following signals:
SIGINT, SIGTERM
immediate termination
Sigquit
Smooth termination
SIGUSR1
Reopen log file
SIGUSR2
Smooth reload all worker processes and reload configuration and binary modules

Tribute to the PHP-FPM author

About
Hi, my name is Andrei Nigmatulin, I am the author of php-fpm.
Since 2004, I have been waiting for someone to make PHP FastCGI to meet the product environment, but I can't wait.
PHP-FPM is the product of knowledge, experience, and ideas in a number of projects using PHP's FastCGI SAPI.
PHP-FPM can be used for public purposes under the GPL. The modified version of Libevent with PHP-FPM binding is released under the BSD protocol.
I need your feedback-new ideas and advice-to improve and optimize PHP FastCGI SAPI. If you have any ideas, comments, additions and suggestions, I will be very happy, very willing to listen, and perhaps will achieve them. e-mail it to me. (Address at the end of this page).
If you want to support the development of PHP-FPM, you can make some donations: Paypal Yandex.Money

15/05/2007-submitted to PHP-FPM for the first time.
Andrei Dot nigmatulin at gmail dot com

Moqtada
PHP-FPM also comes with a more convenient script in the $PREFIX/SBIN/PHP-FPM. Can be maintained with PHP-FPM Start|graceful|restart|stop. You can make it use the configuration file by editing it a little bit.

Nginx_ Notes Sharing _php-fpm detailed

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.