Менеджер процессов FastCGI (FPM)

Содержание

FPM (Менеджер процессов FastCGI) является альтернативной реализацией PHP FastCGI с несколькими дополнительными возможностями обычно используемыми для высоконагруженных сайтов.

Эти возможности включают в себя:

  • продвинутое управление процессами с корректной (graceful) процедурой остановки и запуска;

  • возможность запуска воркеров с различными uid/gid/chroot-окружением, а также запуска на различных портах с использованием разных php.ini (замещение safe_mode);

  • логирование стандартных потоков вывода (stdout) и ошибок (stderr);

  • аварийный перезапуск в случае внезапного разрушения opcode-кэша;

  • поддержка ускоренной загрузки (accelerated upload);

  • "slowlog" - логирование необычно медленно выполняющихся скриптов (не только их имена, но также и их трассировки. Это достигается с помощью ptrace и других подобных утилит для чтения данных исполнения удаленных процессов);

  • fastcgi_finish_request() - специальная функция для завершения запроса и сброса всех буферов данных, причем процесс может продолжать выполнение каких-либо длительных действий (конвертирование видео, обработка статистики и т.п.);

  • Динамическое/статическое порождение дочерних процессов;

  • Базовая информация о статусе SAPI (аналогично Apache mod_status);

  • Конфигурационный файл, основанный на php.ini.

add a note add a note

User Contributed Notes 6 notes

up
22
robin at robinwinslow dot co dot uk
7 years ago
Init script setup
===

You will probably want to create an init script for your new php-fpm. Fortunately, PHP 5.3.3 provides one for you, which you should copy to your init directory and change permissions:

$ cp <php-5.3.3-source-dir>/sapi/fpm/init.d.php-fpm.in /etc/init.d/php-fpm
$ chmod 755 /etc/init.d/php-fpm

It requires a certain amount of setup. First of all, make sure your php-fpm.conf file is set up to  create a PID file when php-fpm starts. E.g.:
----
pid = /var/run/php-fpm.pid
----
(also make sure your php-fpm user has permission to create this file).

Now open up your new init script (/etc/init.d/php-fpm) and set the variables at the top to their relevant values. E.g.:
---
prefix=
exec_prefix=
php_fpm_BIN=/sbin/php-fpm
php_fpm_CONF=/etc/php-fpm.conf
php_fpm_PID=/var/run/php-fpm.pid
---

Your init script is now ready. You should now be able to start, stop and reload php-fpm:

$ /etc/init.d/php-fpm start
$ /etc/init.d/php-fpm stop
$ /etc/init.d/php-fpm reload

The one remaining thing you may wish to do is to add your new php-fpm init script to system start-up. E.g. in CentOS:

$ /sbin/chkconfig php-fpm on

===========

Disclaimer: Although I did just do this on my own server about 20 mins ago, everything I've written here is off the top of my head, so it may not be 100% correct. Also, allow for differences in system setup. Some understanding of what you are doing is assumed.
up
11
joel k
6 years ago
the fpm process supports the USER2 signal, which is used to reload the config file.

kill -USR2 [pid]

should do the trick.
up
8
kokushibyou at gmail dot com
4 years ago
PHP-FPM is FAST - but be wary of using it while your code base is stored on NFS - under average load your NFS server will feel some serious strain. I have yet to find a work around for this bug: https://bugs.php.net/bug.php?id=52312
up
5
dreamcat4 at gmail dot com
3 years ago
Doesn't work? Enable logging!

The php-fpm.log file is a great place to fault-find errors and get to the bottom of a problem. But be sure to enable logging for your specific worker pool. Or you won't see anything!

Example:

To enable error logging for the default [www] worker pool, add this line in the [www] section of your php-fpm.conf:

[www]
catch_workers_output = yes
up
1
ganlvtech at qq dot com
27 days ago
php-fpm is not avaliable on Windows, but you can use IIS or Apache as the "fastcgi process manager".

If you have to use Nginx, here is a solution. Nginx provides a load balancing module. We can distribute the request to different php-cgi.exe process.

<http://nginx.org/en/docs/http/load_balancing.html>
<http://nginx.org/en/docs/http/ngx_http_upstream_module.html>

This is the origin nginx conf.
```
location ~ \.php$ {
    try_files  $uri = 404;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index  index.php;
    include  fastcgi.conf;
}
```

You can replace it by
```
upstream php {
    server  127.0.0.1:9000;
    server  127.0.0.1:9001;
    server  127.0.0.1:9002;
    server  127.0.0.1:9003;
}

location ~ \.php$ {
    try_files  $uri = 404;
    fastcgi_pass  php;
    fastcgi_index  index.php;
    include  fastcgi.conf;
}
```

CAUTION!!

php-cgi.exe process will die after several requests, so you have to restart the php-cgi.exe manually to keep a process listening the port.

DON'T USE THIS SOLUTION IN PRODUCTION!!
up
-1
user at NOSPAM dot example dot com
2 months ago
It is important to note that FPM is not built with the windows binaries.  Many of the guides you may find online rely on php-cgi.exe.  Unfortunately they call it FPM but this is incorrect!

The executable php-cgi.exe that is bundled with the windows binaries is a FastCGI interface but it is *not* FPM (Fastcgi Process Manager).  php-cgi.exe does not have multi-threading or concurrent request support, nor support for any of the FPM configuration options.

The only solid information I've gathered into why FPM is not available is a bug report explaining that FPM is built around fork(), which is not natively available on windows (https://bugs.php.net/bug.php?id=62447).
To Top