How does PHP-FPM work?

Guys, I have a question related to the concept of PHP-fpm . From what I understood through the documentation, it is a module of PHP that manages the requests to the server to avoid high loads, or am I mistaken? How can it benefit in terms of performance?

Author: PauloBoaventura, 2017-05-25

1 answers

PHP-FPM is a process manager for managing FastCGI Sapi (server API) in PHP.

PHP-FPM is a service and not a module. This service runs completely independent of the web server in a separate process and is supported by any FastCGI (Fast Common Gateway Interface) compatible web server.

PHP-FPM is considerably faster than the other methods of processing php scripts, and is also scalable, i.e. it is possible build clusters and expand php's ability to receive requests. See more in What's the difference between using PHP as an Apache module, CGI, FastCGI and command line?.

With PHP-FPM the invoked elements and statements are stored in memory, i.e. it is the implementation of a server-level cache to be reused directly if the request is re-executed (See also OPcache ). For this reason, the PHP file is requested much less this translates into a decrease in machine load (load average) and a better availability of resources so you can do other work.

PHP-FPM can invoke "child process" within the same "worker pool", completely separating the processing of one php script from another. These properties are configured in the "pool" file, by default the pool "www"is set.

Basically the web server sends a php request to the php-FPM which then send to one of your children, and run until the response is delivered, see the diagram below:

insert the description of the image here

Note: it is important to highlight that for php-fpm in tcp mode and in server different from the web server, you must have the php scripts in each of these server.

It is possible to perform various configurations for php-fpm pools, see the example www pool configuration file in www.config:

; Nome da pool 'www'.
;Os comentários são feitos com ";"
[www]
;listen = 127.0.0.1:9000 ; É possível abrir um socket TCP ipv4 ou,
listen = /srv/run/php5-fpm.sock ; Definir um unix socket

;listen.allowed_clients = 127.0.0.1 ; No socket ipv4, é possível restringir  quem se conecta à ele.
; No modo unix socket é preciso definir um usuário e um grupo, o arquivo socket será criado com essas propriedades.
listen.owner = lighttpd
listen.group = lighttpd
listen.mode = 0666


; É preciso configurar sob qual usuário o processo irá rodar.
user = lighttpd
group = lighttpd

; É possível alterar valores do php.ini para uma determinada pool.
php_admin_value[error_log] = /var/log/php-fpm/$pool.log ; É possível usar algumas variáveis, $pool é o nome da pool ("www")
php_admin_value[memory_limit] = 2G ; Vale lembrar que o memory_limit é para cada processamento php, ou seja, um filho pode chegar ao limite de 2G se você definir essa configuração.

; Configuração de como o gerenciador de processo irá administrar os processo filhos.
; Os Valores possíveis são: 
; static - um valor fixo de processos filhos (pm.max_children) é definido e é imutável.
; dynamic - o número de processos filhos é definido de forma dinâmica com base no
; seguintes diretivas:
; pm.max_children - o número máximo de processos filhos que podem fique vivo ao mesmo tempo.
; pm.start_servers - o número de processos filhos criados na inicialização.
; pm.min_spare_servers - o número mínimo de processos filhos em "ocioso" estado (esperando para processar). Se o número
; dos processos "ociosos" for menor do que o definido.
; pm.max_spare_servers - o número máximo de processos filhos em "ocioso" estado (esperando para processar). Se o número
; dos processos "ociosos" for maior do que o definido. Processos ociosos são matados caso o número seja superior ao definido nessa directiva.

pm =  dynamic ; 

;  max_children * php_admin_value[memory_limit] deve ser menor que o Total Memory RAM disponível para o PHP-FPM.
pm.max_children = 120

pm.start_servers = 36 ; Valor padrão: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.min_spare_servers = 15
pm.max_spare_servers = 50
pm.max_requests = 200 ; Número de requisições que um processo recebe antes de ser reiniciado.
pm.process_idle_timeout = 5s ; Tempo de tolerância de um processo ser ocioso, procesos ociosos por mais tempo que isso serão mortos.

There are functions that they may or may not be used in PHP-FPM, such as fastcgi_finish_request which allows you to partially deliver the response by closing the http connection with the client and continue processing something in php in the background.

 41
Author: LeonanCarvalho, 2018-02-19 20:55:03