Рубрики
Uncategorized

Настройка и оптимизация PHP FPM

Автор оригинала: David Wong.

CentOS и другие платформы Linux

/usr/local/php/php
/usr/local/php/etc/php.ini
/usr/local/php/sbin/php-fpm
/usr/local/php/etc/php-fpm.conf

Платформа Mac

/usr/bin/php
/etc/php.ini
/usr/bin/php-fpm
/etc/php-fpm.conf

Потому что я разработал Mac В основном, поэтому для обучения используйте конфигурацию среды MAC.

Сведения о конфигурации PHP FPM

Это подробная конфигурация поиска в php-fpm.conf. Я изменю его соответствующим образом. Конечно, в руководстве по PHP также есть подробное объяснение: http://php.net/manual/zh/inst

pid = /usr/local/var/run/php-fpm.pid
#PID setting must be enabled. It's on Mac platform. The default is var / run / php-fpm.pid in the PHP installation directory. For example, CentOS in / usr / local / PHP / var / run / PHP fpm.pid
error_log  = /usr/local/var/log/php-fpm.log
#Error log, which is on Mac platform, defaults to var / log / php-fpm.log in PHP installation directory, such as Centros in / usr / local / PHP / var / log / php-fpm.log
log_level = notice
#Error level. Register the php-fpm.log record above. The available levels are: alert, error, warning, notice, debug. Default: Notice
emergency_restart_threshold = 60
emergency_restart_interval = 60s
#Indicates that if the number of PHP CGI processes with SIGSEGV or sigbus errors within the set value of emergency_restart_interval exceeds the emergency_restart_threshold, PHP FPM will restart gracefully. These two options generally remain the default values. 0 means' turn off the function '. Default value: 0 (off)
process_control_timeout = 0
#Set the timeout for the subprocess to accept the multiplexing signal of the main process. Available units: s (seconds), m (minutes), H (hours), or D (days). Default unit: s (seconds). Default value: 0
daemonize = yes
#Execute FPM in the background. The default value is yes. If you want to debug, you can change it to No. In FPM, you can run multiple process pools with different settings. These settings can be set individually for each process pool.
listen = 127.0.0.1:9000
#FPM listening port, that is, the address of PHP processing in nginx, is generally the default value. The available formats are: 'IP: port', 'port', '/ path / to / Unix / socket'. Each process pool needs to be set. If nginx and PHP are distributed processing on different machines, IP can be set here.
listen.backlog = -1
#The number of backlogs. Set the semi connection queue length of listen. If - 1 means unlimited, it's up to the operating system. Just comment out this line. Refer to http://www.3gyou.cc/? P = 41 for the meaning of backlog
listen.allowed_clients = 127.0.0.1
#Allow access to the IP white list of fastcgi process. Set any to unlimited IP. If you want to set nginx of other hosts to access this FPM process, set the listen to the local accessible IP. The default is any. Each address is comma separated. If it is not set or empty, any server is allowed to request a connection.
listen.owner = www
listen.group = www
listen.mode = 0666
#UNIX socket setting options, if you use TCP access, here is the comment.
user = www
group = www
#Users and user groups that start the process and UNIX users that FPM processes run must be set. User group, if not set, the default user's group is used.
pm = dynamic 
#PHP FPM process startup mode, PM can be set to static, dynamic and ondemand
#If static is selected, the number of processes is fixed, and pm.max'children specifies the fixed number of subprocesses.
#If dynamic is selected, the number of processes changes dynamically, determined by the following parameters:
Pm.max × children = 50 × maximum number of subprocesses
PM. Start ﹐ servers = 2 ﹐ number of processes at startup, default value: Min ﹐ spare ﹐ servers + (max ﹐ spare ﹐ servers - min ﹐ spare ﹐ servers) / 2
Pm.min ﹣ spare ﹣ servers = 1 ﹣ ensure the minimum number of idle processes. If the number of idle processes is less than this value, a new subprocess will be created
Pm.max? Spare? Servers = 3? To ensure the maximum number of idle processes. If the idle process is greater than this value, clean it up
pm.max_requests = 500
#Set the number of requests served before each subprocess is reborn. It is very useful for third-party modules that may have memory leaks. If set to '0', requests are always accepted. Equivalent to PHP fcgi Max requests environment variable. Default: 0
pm.status_path = /status
#The web address of FPM status page. If it is not set, the status page cannot be accessed. Default value: none. Munin monitoring will use the
ping.path = /ping
#The Ping URL of the FPM monitoring page. If it is not set, the Ping page cannot be accessed. This page is used to externally detect whether FPM is alive and can respond to requests. Please note that it must start with a slash (/).
ping.response = pong
#Used to define the return correspondence of Ping request. Text / plain format text returned as HTTP 200. Default value: pong
access.log = log/$pool.access.log
#The access log of each request is closed by default.
access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"
#Set the format of the access log.
slowlog = log/$pool.log.slow
#Log of slow requests, used in conjunction with request ﹣ slowlog ﹣ timeout, is off by default
request_slowlog_timeout = 10s
#When a timeout of this setting is requested, the corresponding PHP call stack information will be completely written to the slow log. Setting to '0' means' off '
request_terminate_timeout = 0
#Set the timeout abort time for a single request. This option may be useful for scripts in the php.ini setting that do not abort because of some special reasons. Setting to '0' means' off '. You can try to change this option when 502 errors occur frequently.
rlimit_files = 1024
#Set the rlimit limit of the file open descriptor. Default value: the system defined value is 1024 by default, which can be viewed with ulimit-n and modified with ulimit-n 2048.
rlimit_core = 0
#Set the maximum limit value of core rlimit. Available values: 'unlimited', 0 or positive integer. Default value: system defined value
chroot =
#Chroot directory at startup. The defined directory needs to be an absolute path. If not set, chroot will not be used
chdir =
#Set the startup directory to which chdir will be automatically generated at startup. The defined directory needs to be an absolute path. Default value: current directory, or / directory (when chroot)
catch_workers_output = yes
#Redirect stdout and stderr during running to the main error log file. If not set, stdout and stderr will be redirected to / dev / null according to fastcgi rules. Default: null

Конечно, есть некоторые неважные настройки. Давайте поговорим о них, когда мы их используем.

Некоторые важные настройки

Распределение процессов PHP FPM

останься fastcgi В режиме PHP запустит несколько php-fpm процессов, чтобы получить nginx Является ли чем больше процессов, тем быстрее отправляются запросы? Не обязательно! Это зависит от конфигурации вашей машины и объема бизнеса.

Давайте сначала рассмотрим конфигурацию процесса установки?

pm = static | dynamic | ondemand
PM can be set to three types. The most we use is the first two.

PM = static mode

PM = static indicates that the number of PHP FPM subprocesses we create is fixed, so only the parameter pm.max_children = 50 takes effect. When you start PHP FPM, you will start 51 (1 Main + 50 sub) processes together, which is quite spectacular.

PM = dynamic mode

PM = dynamic mode, indicating that the startup process is dynamically allocated and changes dynamically with the number of requests. It is determined by the parameters pm.max, pm.start, pm.min, pm.max.

Как упоминалось выше, давайте еще раз повторим:

Pm.max ABCD children = 50 is the maximum number of child processes that can be created. Must be set. This means that you can only have up to 50 subprocesses.

Pm.start_servers = 20 number of subprocesses created when started with PHP FPM. The default value is: min? Spare? Servers + (max? Spare? Servers - min? Spare? Servers) / 2. It is indicated here that there will be 20 subprocesses to start together.

pm.min_spare_servers = 10 
Set the minimum number of PHP FPM processes when the server is idle. Must be set. If it is idle, it will check that if it is less than 10, it will start several to make up.

pm.max_spare_servers = 30

Установите максимальное количество процессов PHP FPM, когда сервер простаивает. Должно быть установлено. Если количество процессов превышает 30, оно будет закрыто до 30.

Выберите статический или динамический?

Многие люди страдают от фобии. Они не знают, что выбрать?

Общий принцип таков: динамический подходит для небольшой машины с памятью, гибкое распределение процессов, экономия памяти. Статика подходит для больших машин с памятью, а динамическое создание процесса переработки также является потреблением ресурсов сервера.

Если у вас большая память, 8-20 г, в соответствии с процессом PHP FPM 20 м, у 100 будет память 2 Г, тогда вы можете включить статический режим. Если ваша память очень мала, например, всего 256 м, вы должны быть осторожны, чтобы установить ее. Поскольку другие процессы на вашей машине также должны занимать память, лучше всего установить ее в динамическое состояние. Например,, который занимает около 160 м памяти и может измениться в любое время. Этого достаточно для половины посещенных сайтов.

Медленный запрос журнала

Иногда мы страдаем от 500502 проблем. Когда nginx получает приведенный выше код ошибки, можно определить, что что-то не так с внутренним PHP FPM, анализирующим PHP, например, ошибка выполнения, тайм-аут выполнения.

В это время мы можем включить функцию медленного ведения журнала.

slowlog = /usr/local/var/log/php-fpm.log.slow
request_slowlog_timeout = 15s

Когда время ожидания запроса для этой настройки составляет 15 секунд, соответствующая информация о стеке вызовов PHP будет полностью записана в медленный журнал. php-fpm В медленном журнале будет записан номер процесса, имя сценария, конкретный файл, код строки и время выполнения функции

[21-Nov-2013 14:30:38] [pool www] pid 11877
script_filename = /usr/local/lnmp/nginx/html/www.quancha.cn/www/fyzb.php
[0xb70fb88c] file_get_contents() /usr/local/lnmp/nginx/html/www.quancha.cn/www/fyzb.php:2

Из журнала мы можем узнать, что что-то не так с функцией получения содержимого файла в строке 2, поэтому мы можем отследить проблему.

Оригинал: “https://developpaper.com/configuration-and-optimization-of-php-fpm/”