How does PHP-FPM work?

Asked

Viewed 19,287 times

25

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

  • https://secure.php.net/manual/en/install.fpm.php

1 answer

44


PHP-FPM is a process manager to manage Fastcgi SAPI (Server API) in PHP.

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

PHP-FPM is considerably faster than other methods of processing php scripts, and is also scalable, meaning it is possible to build clusters and expand php’s ability to receive requests. See more on What’s the difference of using PHP as a module of Apache, CGI, Fastcgi and command line?.

With PHP-FPM the elements and invoked instructions are stored in memory, that is, it is the implementation of a server-level cache to be reused directly if the request is executed again (See also Opcache) . For this reason, the PHP file is requested much less often, which translates into a decrease of the machine load (load Average) and a better availability of resources for you to do other jobs.

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 "www" pool is set".

Basically the web server sends a php request to php-fpm which then sends it to one of its children, and executes until the answer is delivered, see the diagram below:

inserir a descrição da imagem aqui

NOTE: It is important to note that for php-fpm in tcp mode and in server other than web server, you need to have php scripts in each of these servers.

You can make various settings for php-fpm pools, see the www pool configuration file example at 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 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.

  • 1

    thank you so much for the reply and for the example leonan! helped a lot!

  • Leonan, my server sent an e-mail saying php-fpm is full. I use wordpress, is there anything on the k side that can be done about it? Or they resolve?

  • @Stephanieferreira I never came across this error of "full", but I believe it is (pm) that is fixed, your site has received many hits? if yes, it might be time to increase the php-fpm "pool" or upgrade to a larger server (if you don’t have Russian available to increase php-fpm)

  • @Leonancarvalho Is this for apache?! user = lighttpd group = lighttpd E for NGINX put >>> user = Nginx &&& group = Nginx Correct?

  • @Pauloboaventura generally, for servers where php runs together with the web server, vc uses the same user for both, in many cases it is the www-data , but then it is you who will know which user uses, this will ensure access to folders and files under the web server’s public and private directory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.