- Как включить и отслеживать статус PHP-FPM в Nginx
- Как включить страницу состояния PHP-FPM в Linux
- Php fpm status page
- Configuration
- Query Parameters
- Displayed Information
- Changelog
- php fpm restart nginx ubuntu enable status page, monitor etc
- How to check fpm configuration file errors before restart
- php fpm config test for syntax errors
- How restart Php fpm ubuntu Debian
- How to Enable and Monitor PHP-FPM Status in Nginx
- #1 edit the pho-fpm conf file
- #2 edit nginx default conf add this code
- #3 restart reload nginx
- #4 check status page
- #5 understanding php-fpm status page report
Как включить и отслеживать статус PHP-FPM в Nginx
PHP-FPM (Диспетчер процессов FastCGI) — это альтернативная реализация PHP FastCGI с рядом дополнительных функций, полезных для веб-сайтов любого размера, особенно сайты с высоким трафиком.
Он обычно используется в стеке LEMP (Linux Nginx MySQL/MariaDB PHP); Nginx использует PHP FastCGI для обслуживания динамического контента HTTP в сети. Он используется для обслуживания миллионов запросов PHP для сотен веб-сайтов на веб-серверах в Интернете.
Одной из полезных функций php-fpm является встроенная страница состояния, которая может помочь вам следить за его работоспособностью. В этой статье мы покажем, как включить страницу состояния PHP-FPM в Linux.
Как включить страницу состояния PHP-FPM в Linux
Сначала откройте файл конфигурации php-fpm и включите страницу состояния, как показано.
$ sudo vim /etc/php-fpm.d/www.conf OR $ sudo vim /etc/php/7.2/fpm/pool.d/www.conf #for PHP versions 5.6, 7.0, 7.1
Внутри этого файла найдите и раскомментируйте переменную pm.status_path=/status , как показано на снимке экрана.
Сохраните изменения и закройте файл.
Затем проверьте файл конфигурации PHP-FPM на наличие ошибок, выполнив приведенную ниже команду.
$ sudo php-fpm -t OR $ sudo php7.2-fpm -t
Затем перезапустите службу PHP-FPM, чтобы применить последние изменения.
$ sudo systemctl restart php-fpm OR $ sudo systemctl restart php7.2-fpm
Затем отредактируйте файл конфигурации блока сервера (виртуальный хост) по умолчанию и добавьте в него блок местоположения ниже. Например, в тестовой системе файл конфигурации блока сервера по умолчанию — /etc/nginx/conf.d/default.conf для сайта test.lab.
$ sudo vim /etc/nginx/conf.d/default.conf
Вот блок местоположения, который нужно добавить. В этой конфигурации мы разрешили доступ только к статусу процесса PHP-FPM на локальном хосте с помощью директивы allow 127.0.0.1 из соображений безопасности.
Сохраните файл и закройте его.
Затем перезапустите сервер Nginx, чтобы изменения вступили в силу.
$ sudo systemctl restart nginx
Теперь откройте браузер и введите URL-адрес http://test.lab/status , чтобы просмотреть статус процесса PHP-FPM.
В качестве альтернативы используйте программу curl следующим образом, где флаг -L указывает расположение страницы.
По умолчанию на странице состояния распечатывается только сводка или краткий статус. Чтобы просмотреть статус каждого процесса пула, передайте \full в строке запроса, например:
Вы можете определить выходной формат (JSON, HTML или XML), как показано.
http://www.foo.bar/status?json&full http://www.foo.bar/status?html&full http://www.foo.bar/status?xml&full
Ниже приведены значения, возвращаемые в полном состоянии php-fpm для каждого процесса:
- pid – PID процесса.
- state статус процесса (ожидание, выполнение и т. д.).
- время начала — дата и время начала процесса.
- начать с – количество секунд, прошедших с момента запуска процесса.
- запросы — количество запросов, которые процесс обслужил.
- Длительность запроса – продолжительность запросов в мкс.
- метод запроса — метод запроса (GET, POST и т. д.).
- URI запроса — URI запроса со строкой запроса.
- длина содержимого — длина содержимого запроса (только с POST).
- пользователь — пользователь (PHP_AUTH_USER) (или -, если не задано).
- script — вызывается основной скрипт (или «-», если не задано).
- ЦП последнего запроса — %cpu последнего израсходованного запроса (обратите внимание, что всегда равен 0, если процесс не находится в состоянии простоя).
- память для последнего запроса – максимальный объем памяти, потребляемый последним запросом (всегда равен 0, если процесс не находится в состоянии ожидания).
Это все на данный момент! В этой статье мы объяснили, как включить страницу состояния php-fpm на веб-сервере Nginx. Используйте форму обратной связи ниже, чтобы поделиться с нами своими мыслями.
Php fpm status page
This page provides information on the setup and contents of the FPM status page. See also fpm_get_status() .
Configuration
The FPM status page can be enabled by setting the pm.status_path configuration parameter in the FPM pool configuration.
For security the FPM status page should be restricted to internal requests or known client IPs only as the page reveals request URLs and information about available resources.
Depending on the web server configuration it might be needed to configure the web server to allow requests directly to this path, bypassing any PHP scripts. An example of a configuration for Apache with FPM listening on UDS and pm.status_path set to /fpm-status would look like:
Order Allow,Deny Allow from 127.0.0.1 ProxyPass "unix:/var/run/php-fpm.sock|fcgi://localhost/fpm-status"
After reloading or restarting both FPM and the web server the status page will be accessible from the browser (as long as the request comes from an allowed IP address if the IP restriction was configured).
Query Parameters
The format of the status page output can be altered by specifying one of the following query parameters:
Additional information can also be returned using the full query parameter.
- https://localhost/fpm-status — Brief output in the default text format
- https://localhost/fpm-status?full — Full output in the default text format
- https://localhost/fpm-status?json — Brief output in JSON format
- https://localhost/fpm-status?html&full — Full output in HTML format
Displayed Information
Date/Time values use the unix timestamp format in JSON and XML output, otherwise they use the format resulting in the following example date «03/Jun/2021:07:21:46 +0100» .
Parameter | Description |
---|---|
pool | The name of the FPM process pool. |
proccess manager | The process manager type — static, dynamic or ondemand. |
start time | The date/time that the process pool was last started. |
start since | The time in seconds since the process pool was last started. |
accepted conn | The total number of accepted connections. |
listen queue | The number of requests (backlog) currently waiting for a free process. |
max listen queue | The maximum number of requests seen in the listen queue at any one time. |
listen queue len | The maximum allowed size of the listen queue. |
idle processes | The number of processes that are currently idle (waiting for requests). |
active processes | The number of processes that are currently processing requests. |
total processes | The current total number of processes. |
max active processes | The maximum number of concurrently active processes. |
max children reached | Has the maximum number of processes ever been reached? If so the displayed value is 1 otherwise the value is 0 . |
slow requests | The total number of requests that have hit the configured request_slowlog_timeout . |
Parameter | Description |
---|---|
pid | The system PID of the process. |
state | The state of the process — Idle, Running, . |
start time | The date/time at which the process started. |
start since | The number of seconds since the process started. |
requests | The total number of requests served. |
request duration | The total time in seconds spent serving requests. |
request method | The HTTP method of the last served request. |
request uri | The URI of the last served request (after webserver processing, it may always be /index.php if you use a front controller pattern redirect). |
content length | The length of the request body, in bytes, of the last request. |
user | The HTTP user ( PHP_AUTH_USER ) of the last request. |
script | The full path of the script executed by the last request. This will be ‘-‘ if not applicable (eg. status page requests). |
last request cpu | The %cpu of the last request. This will be 0 if the process is not Idle because the calculation is done when the request processing is complete. |
last request memory | The maximum amount of memory consumed by the last request. This will be 0 if the process is not Idle because the calculation is done when the request processing is complete. |
Note:
All values are specific to the pool and are reset when FPM is restarted.
Note:
OpenMetrics format output uses different parameter types to better suit the OpenMetrics format. The parameters and descriptions of their values are included in the OpenMetrics format output.
Changelog
php fpm restart nginx ubuntu enable status page, monitor etc
How to check fpm configuration file errors before restart
root@localhost:~# php-fpm7.4 -t
[30-Jul-2021 17:05:34] NOTICE: configuration file /etc/php/7.4/fpm/php-fpm.conf test is successful
php fpm config test for syntax errors
root@murali:~# php-fpm8.1 -t
[18-Jul-2023 04:29:08] NOTICE: configuration file /etc/php/8.1/fpm/php-fpm.conf test is successful
How restart Php fpm ubuntu Debian
systemctl restart php7.4-fpm
systemctl reload php7.4-fpm
How to Enable and Monitor PHP-FPM Status in Nginx
#1 edit the pho-fpm conf file
#2 edit nginx default conf add this code
#3 restart reload nginx
#4 check status page
pool: www process manager: dynamic start time: 02/Apr/2021:19:16:20 +0000 start since: 1588836 accepted conn: 189149 listen queue: 0 max listen queue: 19 listen queue len: 65536 idle processes: 15 active processes: 1 total processes: 16 max active processes: 31 max children reached: 0 slow requests: 0
pool: www process manager: dynamic start time: 02/Apr/2021:19:16:20 +0000 start since: 1589136 accepted conn: 189184 listen queue: 0 max listen queue: 19 listen queue len: 65536 idle processes: 15 active processes: 1 total processes: 16 max active processes: 31 max children reached: 0 slow requests: 0 ************************ pid: 28970 state: Idle start time: 17/Apr/2021:05:04:18 +0000 start since: 344258 requests: 2510 request duration: 108062 request method: POST request URI: /wp-admin/admin-ajax.php content length: 6490 user: - script: /var/www/html/raazkumar.com/wp-admin/admin-ajax.php last request cpu: 74.03 last request memory: 2097152 ************************ pid: 28874 state: Idle start time: 17/Apr/2021:04:51:08 +0000 start since: 345048 requests: 2541 request duration: 114807 request method: GET request URI: /index.php content length: 0 user: - script: /var/www/html/raju/index.php last request cpu: 60.97 last request memory: 2097152 ************************ pid: 2205 state: Idle start time: 20/Apr/2021:11:57:32 +0000 start since: 60264 requests: 425 request duration: 355489 request method: POST request URI: /wp-cron.php?doing_wp_cron=1618980078.5080909729003906250000 content length: 0 user: - script: /var/www/html/sarkariresultz.in/wp-cron.php last request cpu: 61.89 last request memory: 12582912 ************************ pid: 28951 state: Idle start time: 17/Apr/2021:05:03:05 +0000 start since: 344331 requests: 2522 request duration: 130015 request method: POST request URI: /wp-admin/admin-ajax.php content length: 67 user: - script: /var/www/html/raazkumar.com/wp-admin/admin-ajax.php last request cpu: 69.22 last request memory: 2097152 ************************ pid: 28964 state: Idle start time: 17/Apr/2021:05:04:16 +0000 start since: 344260 requests: 2512 request duration: 384968 request method: GET request URI: /index.php content length: 0 user: - script: /var/www/html/sarkariresultz.in/index.php last request cpu: 77.93 last request memory: 31457280 ************************ pid: 28975 state: Idle start time: 17/Apr/2021:05:04:23 +0000 start since: 344253 requests: 2502 request duration: 5912 request method: GET request URI: /index.php content length: 0 user: - script: /var/www/html/jojowealth.com/index.php last request cpu: 169.15 last request memory: 2097152 ************************ pid: 28859 state: Running start time: 17/Apr/2021:04:50:59 +0000 start since: 345057 requests: 2540 request duration: 3227 request method: GET request URI: /status?full content length: 0 user: - script: - last request cpu: 0.00 last request memory: 0
#5 understanding php-fpm status page report
pool | www |
---|---|
process manager | dynamic |
start time | 14/Jul/2020:16:12:35 +0000 |
start since | 43224 // number of seconds since the process has started. |
accepted conn | 3384 // accepted request from nginx |
listen queue | current ques |
max listen queue | maximum queue still server start requests in the queue of pending connections |
listen queue len | maximum length 65536 .. sysctl conf has to modify |
idle processes | 2 |
active processes | 1 |
total processes | 3 |
max active processes | 3 // max active processes still the server started |
max children reached | 0 // how many times its reached max process increase (php fpm pool configuration) |
slow requests | 0 // you have enable first also available at /var/log/phpslow |
request duration – in microseconds (1000th of milli second)
request method – GET, POST,
request URI – request URI with the query string.
content length – content length of the request (only with POST).
user – user (PHP_AUTH_USER) (or ‘-‘ if not set).
script – main script called (or ‘-‘ if not set).
last request cpu – %cpu the last request consumed (note that it’s always 0 if the process is not in Idle state).
last request memory – max amount of memory the last request consumed