配置Linux PHP-FPM(FastCGI Process Manager)以支持高并发需要考虑多个方面,包括调整进程管理参数、优化网络设置、监控和日志记录等。以下是一些关键步骤和建议:
PHP-FPM的配置文件通常位于 /etc/php/版本号/fpm/pool.d/www.conf
。你需要编辑这个文件来调整进程管理参数。
; Start a new pool named 'www'.
[www]
; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'unix:/path/to/unix/socket' - to communicate on a unix socket.
; Note: This value is mandatory.
listen = /run/php/php7.4-fpm.sock
; Set listen(2) backlog.
; Default: 128
;listen.backlog = 511
; Listen for IPv6 only connections:
;listen.allow_ipv6 = no
; Specify the user of the FPM child processes.
; Note: The user must have permissions to read and write to the socket file.
user = www-data
group = www-data
; Set the process manager to dynamic.
; Dynamic mode will adjust the number of child processes according to the
; workload.
pm = dynamic
; The number of child processes to start initially.
;pm.start_servers = 5
; The minimum number of child processes which are kept in idle state.
;pm.min_spare_servers = 5
; The maximum number of child processes which are kept in idle state.
;pm.max_spare_servers = 35
; The number of child processes considered 'idle' and ready to be reused.
;pm.max_requests = 500
根据你的服务器资源和预期的并发量,调整 pm.start_servers
, pm.min_spare_servers
, pm.max_spare_servers
和 pm.max_requests
参数。
pm.start_servers
: 初始启动的子进程数。pm.min_spare_servers
: 最小空闲子进程数。pm.max_spare_servers
: 最大空闲子进程数。pm.max_requests
: 每个子进程处理的最大请求数,防止内存泄漏。编辑 /etc/sysctl.conf
文件,添加或修改以下参数:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
然后运行 sysctl -p
使更改生效。
在 php.ini
文件中启用慢查询日志:
slow_query_log = 1
slow_query_log_file = /var/log/php-slow.log
long_query_time = 2
使用 php-fpm status
命令监控PHP-FPM的状态。你可以创建一个脚本来定期检查并发送警报。
确保启用了OPcache来加速PHP脚本的执行:
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
确保PHP-FPM进程有足够的文件描述符限制:
ulimit -n 65535
并在 /etc/security/limits.conf
中添加:
* soft nofile 65535
* hard nofile 65535
在应用这些更改后,进行压力测试以确保服务器能够处理预期的并发量。根据测试结果,进一步调整配置参数。
通过以上步骤,你可以有效地配置Linux PHP-FPM以支持高并发。记住,每个服务器的环境和需求都不同,因此需要根据实际情况进行调整和优化。