The introduction

PHP+Nginx has been used for so long, do you know how they communicate with each other? This time, do a real PHPer (I covered CGI, FastCGI, and PHP-fpm thoroughly in the last article, so I won’t go into detail about these concepts in this article).

PHP-FPM

Php-fpm stands for PHP FastCGI Process Manager. Php-fpm is an implementation of FastCGI and provides Process management capabilities. FastCGI processes include master and worker processes. The master process has only one, which is responsible for listening to the port and receiving Nginx requests, while the worker process generally has multiple (configurable) processes. Each process is embedded with a PHP interpreter, where THE PHP code is actually executed.

Nginx

Nginx (” Engine X “) is a high-performance HTTP and reverse proxy server as well as an IMAP/POP3/SMTP server. It’s important to understand Nginx, what are forward and reverse proxies

Forward agent

For example, we visit foreign websites, such as Google, Facebook. We need to use VPN to access. When we use VPN to access foreign websites, it is actually a process of forward proxy, as shown in the figure above:

While the VPN is perceived by the user (because the user needs to configure the connection), it is not perceived by the Google server (the Google server only knows when an HTTP request is coming). So a server that is perceived by the user but not by the server is a forward proxy server (VPN)

The reverse proxy

Take Nginx as the reverse proxy server to realize load balancing as an example. Suppose we visit Baidu at this time, and look at the picture:

When a user visits Baidu, all the requests will go to a reverse proxy server, which will send the requests to a later server for processing. At this time, the proxy server is actually invisible to users. What users perceive is that baidu’s server returns results to them, and they do not know the existence of the proxy server. In other words, it is not perceived by the user, but is perceived by the server. It is called the reverse proxy server (Nginx).

PHP – FPM + Nginx communication

FastCGI aims to reduce the overhead of the interaction between a Web server and a CGI program, thus allowing the server to handle more Web requests simultaneously. Unlike CGI, which creates a new process for each request, FastCGI uses a continuous process to handle a series of requests. These processes are managed by the FastCGI process manager, not the Web server.

Use diagrams to understand phP-FPM and Nginx communication(1) When Nginx receives HTTP requests (dynamic requests), it initializes the FastCGI environment. (Mode_fastCGI module is initialized for the Apache server and ngx_http_fastcgi_module for the Nginx server)

(2) When we configure Nginx to parse PHP requests, we usually have a configuration line like this:

Fastcgi_pass 127.0.0.1:9000;

Copy the code

Or look like this:

fastcgi_pass  unix:/tmp/php-cgi.sock;

Copy the code

It is a communication vehicle (or means of communication) between Nginx and PHP-fpm to let Nginx know where to send dynamic requests. (The differences between these two configurations are covered later.)

(3) Nginx forwards the request to the main FastCGI process via socket

(4) The FastCGI main process selects an idle worker process to connect, and Nginx sends CGI environment variables and standard input to the worker process (PHP-CGI).

(5) Worker process returns standard output and error information to Nginx from the same socket connection after finishing processing

(6) The worker process closes the connection and waits for the next connection

Let’s describe the communication between PHP and Nginx, not from a configuration perspective

  • As we know, Nginx also has master and worker processes, and the worker process directly processes every network request
  • In fact, within the Nginx+PHP architecture, PHP can be seen as a CGI program, so the PHP-Fpm process manager is created to handle these PHP requests. Php-fpm, like nginx, listens to ports (nginx listens to port 8080 by default, phP-fpm listens to port 9000 by default), and has a master and worker process. The worker handles every PHP request
  • About FastCGI: FastCGI is a protocol. Php-fpm is one of several process managers that implement the FastCGI protocol. Php-fpm is a fastCGI process management service that listens for ports. By default, phP-Fpm listens for port 9000
  • The fastcgi configuration file is stored in the nginx.conf directory. There are two types of fastcgi configuration files:
Fastcgi. Conf and fastcgi_params.

Different versions of Nginx have different configuration files with one important difference: the fastcgi_parames file is missing the following configuration:

fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;

Copy the code

We can open the fastCgi_params file and add the above lines, or we can add them dynamically where we want to use the configuration. The configuration takes effect

  • When a PHP request needs to be processed, the nginx worker process will hand over the request to the PHP-fpm worker process for processing, which means that nginx calls PHP. In fact, strictly speaking, nginx indirectly calls PHP (reverse proxy mode).

I have configured the nginx configuration to parse PHP normally. Let me introduce the meaning of each configuration line

server{

 listen 8080;

 index index.php

 root /work/html/;



 location ~ [^/]\.php(/|$)

 {

      root         /work/html/;  

Fastcgi_pass 127.0.0.1:9000;

        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;  

        include        fastcgi_params;   

 }

 access_log /work/html/logs/test.log;

}

Copy the code
  1. The first curly brace, server{}, represents a separate server
  2. Listen 8080: indicates that the server listens to port 8080
  3. The location ~ [r]. ^ / PHP / | ${} : can represent a matching corresponding to the location of the uri used to match a uri, and uri of the matched request custom logic, configuration. Here the location, matching all take. PHP request uri, such as http://192.168.244.128:8011/test.php/asdasd, http://192.168.244.128:8011/index.php, etc
  4. Root /work/ HTML / : Request the root directory of the resource and tell the URI matching the location to /work/ HTML/folder to find the resource with the same name
  5. Fastcgi_pass 127.0.0.1:9000: This line of code treats the URI request entering the location as a CGI program and sends the request to port 9000 for processing by phP-fpm (phP-fpm configuration will see that it listens to this port).
  6. fastcgi_param SCRIPT_FILENAME fastcgi_script_name; Added a line of fastCGI configuration to SCRIPT_FILENAME to inform the admin process of the name of the CGI script. Since my nginx only has a fastcgi_params file, not a fastcgi.conf file, it is necessary to add this line dynamically in order for php-fpm to know the actual value of SCRIPT_FILENAME
  7. include fastcgi_params; Import the FastCGI configuration file

fastcgi_pass

Nginx and PHP-fpm can communicate with each other in two ways: TCP Socket and Unix Socket.

Tcp Socket is IP plus port, and can cross servers. UNIX sockets do not go over the network and can only be used when Nginx and PHP-fpm are on the same server. Which one you use depends on your PHP-fpm configuration

Tcp Socket: fastcgi_pass 127.0.0.1:9000 in nginx.conf. Php-fpm. conf: listen=127.0.0.1:9000;

Unix Domain Socket: nginx.conf: fastcgi_pass Unix :/ TMP/php-pfm.sock; Php-fpm: listen = / TMP /php-fpm.sock; (PHp-fpm. sock is a file generated by PHP-fpm)

For example, the communication between Nginx and PHP-fpm is as follows: Tcp Socket:

Nginx <=> socket <=> TCP/IP <=> socket <=> PHP-FPM

Copy the code

(This is the case when Nginx and PHP-fpm are on the same machine)

Nginx < = > socket < = > TCP/IP < = > < = > the physical router < = > < = > the physical TCP/IP < = > socket < = > PHP - FPM

Copy the code

Unix sockets:

Nginx <=> socket <=> PHP-FPM

Copy the code

include fastcgi_params;

There are many fasgcgi_* configurations in nginx. More configurations can be found in the nginx.conf directory. The differences between fastcgi.conf and fastcgi_params are described above. Take a look at the contents:Everything here is passed to the FASTCGI process managed by PHP-fpm. Why are these passed on? I’m sure you’ve all used the global variable $_SERVER, where the edge value is derived from this configuration. You can see REMOTE_ADDR in fastcgi_params, which is the client address. PHP can get the client information because of the fastCgi_params configuration in Nginx. More ngx_http_fastcgi_module module content, we can see the official document: http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html

PHP – FPM. Conf configuration

Familiarity with PHP-FPM configuration can help optimize server performance

emergency_restart_threshold = 60

emergency_restart_interval = 60s

Copy the code

Indicates that phP-fpm will restart gracefully if the number of PHP-CGI processes with SIGSEGV or SIGBUS errors in the emergency_restart_interval exceeds the emergency_restart_threshold. These two options are generally left to their default values

process_control_timeout = 0

Copy the code

Set the timeout period for the child process to receive the multiplexing signal from the main process. Available units: s(second), m(minute), h(hour), or d(day) Default unit: s(second). Default value: 0.

Listen = 127.0.0.1:9000

Copy the code

The FPM listening port is the address processed by PHP in nginx. Available format is: ‘IP: port’, ‘port’, ‘/ path/to/Unix/socket. Each process pool needs to be set.

request_slowlog_timeout = 10s

# When a request for the timeout time is set, the corresponding PHP call stack information will be written to the slow log. Setting it to '0' means' Off '

 

slowlog = log/$pool.log.slow

Record logs of slow requests. Used with request_slowLog_timeout

Copy the code

The following parameters are important:

pm

PM refers to the Process Manager and specifies how the process manager controls the number of child processes. It is mandatory and supports three values

(1)static: use a fixed number of children, specified by pm.max_children (maximum number of children that can survive simultaneously)

(2) Dynamic: Dynamically adjust the number of child processes based on the following parameters, at least one child process (using the following configurations)

Pm. start_Servers: Number of child processes created during startup. The default value is min_spare_Servers + max_spare_servers-min_spare_Servers) / 2



Pm. min_spare_Servers: Minimum number of idle child processes, if not enough, new child processes are created automatically



Pm. max_spare_servers: Maximum number of idle child processes, if exceeded, some child processes will be killed

(3) Ondemand: the child process is not created at startup, but only created when a new request arrives

pm.max_children

Pm. process_IDLE_timeout Specifies the idle timeout period for the child process. If the timeout period is long enough that no new requests can be served, it will be killed



The difference between:

If PM is set to static, only pm.max_children is valid. The system will start the number of PHP-fpm processes

If PM is set to dynamic, the Pm. max_children parameter is invalid and the next three parameters take effect

Pm. start_servers the pm-fpm process will be started at the start of the php-fpm run.

Then, the number of PHP-FPM processes is dynamically adjusted between Pm. min_spare_Servers and pm. max_spare_Servers according to the system requirements



There is one more important configuration:

pm.max_requests

The maximum number of requests for service per child process. If this value is exceeded, the child process will be automatically restarted. This parameter can be useful when dealing with memory leaks in third-party libraries. The default value is 0, indicating that the child process can continuously request service

Copy the code

PHP – FPM process pool

Php-fpm. conf is configured with a pool of processes by default.Now we perform: ps – aux | grep PHP – FPMWe will see that there is a master and 10 worker processes, as we configured (WWW for the process pool name).

To configure more than one, do this: You can configure which process pool to use at fastcgi_pass in nginx

Reference:

https://www.php.cn/php-weizijiaocheng-393152.html https://www.cnblogs.com/skynet/p/4173450.html https://blog.csdn.net/afring/article/details/93880216 https://www.cnblogs.com/ahaii/p/5776809.html