Actual combat Nginx and PHP (FastCGI) installation, configuration and optimization ____php

Source: Internet
Author: User
Tags diff fpm php error php script php source code phpinfo wrapper nginx server


from:http://ixdba.blog.51cto.com/2895551/806622









first, what is FastCGI
FastCGI is a scalable, high-speed interface for communicating between HTTP server and dynamic scripting languages. Most popular HTTP servers support FASTCGI, including Apache, Nginx, and lighttpd, and fastcgi are supported by a number of scripting languages, including PHP.
FastCGI is from the CGI development improvement. The main disadvantage of the traditional CGI interface approach is poor performance, because every time the HTTP server encounters a dynamic program, it needs to restart the script parser to perform the parsing, and the result is returned to the HTTP server. This is almost not available when handling high concurrent access. In addition, the traditional CGI interface is also very poor security, it is now rarely used.
The FastCGI interface adopts the C/s structure, which separates the HTTP server from the script resolution server, and initiates one or more script resolution Daemons on the script resolution server. Each time the HTTP server encounters a dynamic program, it can be delivered directly to the fastcgi process to execute, and the resulting results are returned to the browser. This approach allows HTTP servers to handle static requests in a single-minded manner or to return the results of a dynamic script server to the client, which greatly improves the performance of the entire application system.



Second, nginx+fastcgi operation principle
Nginx does not support direct calls or parsing of external programs, all external programs (including PHP) must be invoked through the FastCGI interface. FastCGI interface in Linux is the socket, (this socket can be a file socket, can also be an IP socket). To invoke a CGI program, you also need a fastcgi wrapper (wrapper can be understood as a program to start another program), which is bound to a fixed socket, such as a port or a file socket. When Nginx sends a CGI request to this socket, the FastCGI interface wrapper the request and derives a new thread that invokes the interpreter or external program to process the script and read the return data; Wrapper then passes the returned data through the FastCGI interface to the nginx along the fixed socket, and Nginx sends the returned data to the client, which is the whole operation of the nginx+fastcgi. Detailed procedures, as shown in Figure 1.






Fig. 1 Operation Principle of nginx+fastcgi



third. spawn-fcgi and PHP-FPM



As described earlier, the FastCGI interface method initiates one or more daemons on a script resolution server to parse dynamic scripts, which are fastcgi process managers, or fastcgi engines, SPAWN-FCGI and PHP-FPM are the two fastcgi process managers that support PHP.
The following is a brief introduction to the similarities and differences between spawn-fcgi and PHP-FPM.



SPAWN-FCGI is a part of the HTTP server lighttpd, has now become a stand-alone project, generally with LIGHTTPD with the use to support PHP, but ligttpd spwan-fcgi in high concurrent access, There is a memory leak or even an automatic reboot of the fastcgi problem.



Nginx is a lightweight HTTP server, you must use a Third-party fastcgi processor to be able to parse the PHP, so the combination of nginx+spawn-fcgi can also achieve the interpretation of PHP, not too much to tell.



PHP-FPM is also a third-party fastcgi process manager, which is developed as a patch in PHP, also need to compile with the PHP source code when installing, that is to say, PHP-FPM is compiled into the PHP kernel, so it is better to handle the performance At the same time it is much better at handling high concurrency than the spawn-fcgi engine, so it is recommended that nginx+php/php-fpm this combination to parse PHP.



The main advantage of FastCGI is the separation of the dynamic language and HTTP server, so nginx and PHP/PHP-FPM are often deployed on different servers to share the pressure of the front-end Nginx server, so that the nginx single-minded processing of static requests and forwarding dynamic requests, while PHP The/PHP-FPM server is dedicated to parsing PHP dynamic requests.



fourth. installation and optimization of PHP and PHP-FPM



1. Download installation package
Download the PHP source package from the Www.php.net official website, which is a stable version of php-5.2.13.tar.gz.
Download the corresponding PHP-FPM source package from http://php-fpm.org/downloads/, here is php-5.2.13-fpm-0.5.13.diff.gz.
Note that when downloading the package version, try to keep the PHP and PHP-FPM versions consistent, and compatibility issues can occur if the versions are too different.



2. Configure the installation environment
Installation of PHP requires the following package support, if not installed, please install yourself.



GCC gcc-c++ libxml2 libxml2-devel autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel zlib zlib-de Vel glibc glibc-devel glib2 glib2-devel


Because of the uncertainty of each Linux system version, the reader can install the corresponding software library in the course of installing PHP according to the error message.



3. Start compiling and installing PHP and PHP-FPM
Compiling and installing PHP and PHP-FPM is very simple, the following is the installation process:



[Root@localhost Local] #tar zxvf php-5.2.13.tar.gz [root@localhost Local] #gzip-cd php-5.2.13-fpm-0.5.13.diff.gz | patch-d PHP-5.2.13-P1 [Root@localhost Local] #cd php-5.2.13 [root@localhost php-5.2.13]#./configure--prefix=/usr/lo cal/php--enable-fastcgi--enable-fpm [root@localhost php-5.2.13] #make [root@localhost php-5.2.13] #make install [roo T@localhost PHP-5.2.13]CP Php.ini-dist/usr/local/php/lib/php.ini


The second step is to add php-fpm as a patch into the PHP source code.
In the "./configure" compilation option, specify that PHP be installed under/usr/local, "--enable-fastcgi" is enabled for fastcgi support for PHP, and "--ENABLE-FPM" is the fastcgi support for FPM mode activation.
You can add a lot of compilation options when compiling PHP, but there are no more compilation options to introduce PHP's fastcgi functionality.



4. Configuration and Optimization php-fpm
The global configuration file for PHP is php.ini, and in the previous steps, the file has been copied to/usr/local/php/lib/php.ini. PHP.ini can be configured according to the different requirements of each application.
The following highlights the configuration files for the PHP-FPM engine.



Depending on the installation path specified above, the default profile for PHP-FPM is/usr/local/php/etc/php-fpm.conf.
Php-fpm.conf is a plain text file in XML format, and its contents are easily understood. Here are a few key configuration tags:



The label listen_address is the IP address and port on which the FASTCGI process is configured to monitor, and the default is 127.0.0.1:9000.
<value name= "Listen_address" >127.0.0.1:9000</value>



The label display_errors is used to set whether to display PHP error messages, default is 0, no error message is displayed, set to 1 to display PHP error messages.
<value name= "Display_errors" >0</value>



Label user and group are used to set up users and groups of users who are running the fastcgi process. Note that the user and user groups specified here are consistent with the user and user groups specified in the Nginx configuration file.
<value name= "User" >nobody</value>
<value name= "group" >nobody</value>



Label Max_children the number of processes that are used to set fastcgi. According to the official recommendation, servers less than 2GB of memory can open only 64 processes, and servers with 4GB or more memory can open 200 processes.
<value name= "Max_children" >5</value>



The label request_terminate_timeout is used to set the time when the fastcgi executes the script. The default is 0s, which is unlimited execution, can be modified according to the situation.
<value name= "Request_terminate_timeout" >0s</value>



The label rlimit_files is used to set the PHP-FPM limit on open file descriptors, which defaults to 1024. The value of this tag must be associated with the number of open files for the Linux kernel, for example, to set this value to 65535, you must perform ' ULIMIT-HSN 65536 ' on the Linux command line.
<value name= "Rlimit_files" >1024</value>



The label max_requests indicates that each children will be closed after the maximum number of requests processed, and the default setting is 500.
<value name= "Max_requests" >500</value>



The label allowed_clients is used to set the IP address that allows access to the FASTCGI process parser. If you do not specify an IP address here, the PHP resolution request forwarded by NGINX will not be accepted.
<value name= "Allowed_clients" >127.0.0.1</value>



5. Managing the FASTCGI process
After you configure PHP-FPM, you can start the fastcgi process. There are two ways to start the fastcgi process:



/usr/local/php/bin/php-cgi--fpm or/USR/LOCAL/PHP/SBIN/PHP-FPM start


It is recommended that the FASTCGI process be started in the second way.
/USR/LOCAL/PHP/SBIN/PHP-FPM also has other parameters, specifically start|stop|quit|restart|reload|logrotate.
The meaning of each startup parameter is as follows:



start, start the PHP fastcgi process.   stop, forced to terminate the PHP fastcgi process.   quit, smooth end of PHP fastcgi process.   restart, restart PHP's fastcgi process.   reload, Reload PHP's php.ini. logrotate, re-enable log files.


Reload is an important parameter that can reload the changed php.ini without interrupting the fastcgi process in PHP, so you can smooth change the PHP settings in fastcgi mode by PHP-FPM.




After the fastcgi process starts, the IP address and port on which it listens is started, and the information can be viewed through PS and netstat.



 [root@localhost php]# netstat -antl|grep 9000   tcp         0      0 127.0.0.1:9000               0.0.0.0:*                    LISTEN     [ root@localhost php]# ps -ef|grep php-cgi   root      3567      1     0  17:06 ?        00:00:00 /usr/local/php/bin/php-cgi --fpm --fpm-config /usr/local/php/ etc/php-fpm.conf   nobody    3568  3567  0  17:06 ?         00:00:00 /usr/local/php/bin/php-cgi --fpm -- Fpm-config /usr/local/php/etc/php-fpm.conf   nobody    3569  3567  0  17:06  ?         00:00:00 /usr/local/php/bin/php-cgi --fpm -- fpm-config /usr/local/php/etc/php-fpm.conf   nobody    3570  3567   0  17:06 ?        00:00:00 /usr/local/php/ bin/php-cgi --fpm --fpm-config /usr/local/php/etc/php-fpm.conf   nobody     3571  3567  0  17:06 ?         00:00:00 /usr/local/php/bin/php-cgi --fpm --fpm-config /usr/local/php/etc/ php-fpm.conf   nobody    3572  3567  0  17:06 ?         00:00:00 /usr/local/php/bin/php-cgi --fpm -- Fpm-config /usr/local/php/etc/php-fpm.conf   root      3583  3524  0 17:09  pts/1    00:00:00 grep php-cgi  


fifth. Configure NGINX to support PHP
The installation of Nginx is particularly simple, which has been described in detail before and is no longer described here. The following focuses on Nginx how to parse the PHP through the PHP-FPM fastcgi process.
Because Nginx itself will not parse PHP, so to achieve nginx support for PHP, is actually the request to the PHP page to the fastcgi process to listen to the IP address and port. If the PHP-FPM as a dynamic application server, then Nginx is actually a reverse proxy server. Nginx through the reverse proxy function to achieve the parsing of PHP, which is the nginx implementation of PHP dynamic analysis of the principle.
This assumes that the Nginx installation directory is/usr/local, then the Nginx configuration file path is/usr/local/nginx/conf/nginx.conf. The following is a virtual host configuration instance that supports PHP resolution under Nginx.



        server {   include port.conf;     server_name www.ixdba.net ixdba.net;       location / {   index index.html index.php;     root /web/www/www.ixdba.net;   &nbsp      location ~ \.php$ {               root           html ;               fastcgi_pass    127.0.0.1:9000;               fastcgi_index   index.php;               fastcgi_param  script_ filename  html$fastcgi_script_name;   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp; include        fastcgi_params;   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}  }    


Through the location instruction, all PHP-suffix files are handed to 127.0.0.1:9000 for processing, and the IP address and port here are the IP addresses and ports that the fastcgi process listens to.
The fastcgi_param directive specifies the home directory where the PHP dynamic program is placed, which is the path specified before $fastcgi_script_name, which is the/usr/local/nginx/html directory. It is recommended that this directory be consistent with the root directory specified by the Nginx virtual host and, of course, inconsistent.
The Fastcgi_params file is a parameter profile of the fastcgi process, and a file is generated by default after Nginx is installed, including the fastcgi parameter configuration file through the include directive.
Next, start the Nginx service.
/usr/local/nginx/sbin/nginx
So far, nginx+php has been configured to complete.



Sixth, test Nginx to PHP parsing function
Here, create a phpinfo.php file under the/usr/local/nginx/html directory, which reads as follows:
<?php phpinfo ();?>
Then access http://www.ixdba.net/index.html through the browser, the default will be in the browser display "Welcome to nginx!" Indicates that the Nginx is running correctly.
Then, access to http://www.ixdba.net/phpinfo.php in the browser, PHP installation configuration and Feature list statistics will appear if PHP can parse correctly.



seventh. examples to explain the optimization of fastcgi parameters in Nginx
After the configuration completes nginx+fastcgi, in order to ensure the high speed and stable operation of PHP environment under Nginx, some fastcgi optimization instructions need to be added. An example of an optimization is given below, adding the following code to the HTTP hierarchy in the Nginx master configuration file.



Fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=test:10m inactive= 5m;     fastcgi_connect_timeout 300;     fastcgi_send_timeout 300;      fastcgi_read_timeout 300;     fastcgi_buffer_size 64k;     fastcgi_buffers 4 64k;     fastcgi_busy_buffers_size 128k;     fastcgi_temp_file_write_size 128k;     fastcgi_cache test;     Fastcgi_ cache_valid 200 302 1h;     fastcgi_cache_valid 301 1d;     fastcgi_cache_valid any 1m;     


The following is an introduction to the meaning of the above code.
The first line of code is to specify a file path, directory structure level, key area store time, and inactive deletion time for the fastcgi cache.
FASTCGI_CONNECT_TIMEOUT specifies the time-out period for connecting to the backend fastcgi.
FASTCGI_SEND_TIMEOUT Specifies the timeout for transferring requests to fastcgi, which is the timeout for sending requests to fastcgi after two handshakes have been completed.
FASTCGI_READ_TIMEOUT Specifies the timeout for receiving the fastcgi answer, which is the timeout for receiving the fastcgi answer after two handshakes have been completed.



Fastcgi_buffer_size is used to specify how much buffer is needed to read the first part of the fastcgi answer, which means that the first part of the answer (the answer header) will be read using a 1 64KB buffer, and can be set to Fastcgi_ The buffer size specified by the buffers option.



Fastcgi_buffers specifies how much and how much buffer the local needs to use to buffer fastcgi reply requests. If a PHP script produces a page size of 256KB, it is allocated 4 64KB buffers to cache, and if the page size is greater than 256KB, the portion greater than 256KB is cached to the path specified by fastcgi_temp, but this is not a good method. Because data processing in memory is faster than hard disk. Generally this value should be the site in the PHP script generated by the middle of the page size, if the site most of the script generated by the page size of 256KB, then you can set this value to "16k", "4 64k" and so on.



The default value for Fastcgi_busy_buffers_size is twice times that of Fastcgi_buffers.


The

Fastcgi_temp_file_write_size indicates how much data blocks are used when writing to the cached file, and the default value is twice times that of Fastcgi_buffers. Fastcgi_cache indicates that the FASTCGI cache is turned on and given a name. Turning on caching is useful for reducing CPU load and preventing 502 errors, but opening the cache can cause many problems, depending on the situation.
Fastcgi_cache_valid, fastcgi is used to specify the cache time for the answer code, and the value in the instance indicates that the 200 and 302 responses are cached for one hours, 301 replies are cached 1 days, and the other responses are cached for 1 minutes.


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.