在LNMP(Linux, Nginx, MySQL, PHP-FPM)架构中,PHP-FPM(FastCGI Process Manager)的优化配置对于提升网站性能至关重要。以下是一些常见的优化建议:
PHP-FPM提供了多种进程管理模式,包括dynamic
、ondemand
和static
。默认情况下,大多数系统使用dynamic
模式。
dynamic: 根据负载动态调整进程数。
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
ondemand: 只在需要时启动进程。
pm = ondemand
pm.process_idle_timeout = 10s
static: 固定数量的进程。
pm = static
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
增加请求队列长度可以减少FastCGI进程的创建和销毁开销。
request_terminate_timeout = 0
慢查询日志可以帮助你识别和优化数据库查询。
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
根据应用需求调整PHP的内存限制。
memory_limit = 128M
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
确保Nginx配置与PHP-FPM协同工作,减少不必要的开销。
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
定期监控PHP-FPM的性能和日志,以便及时发现和解决问题。
log_level = notice
catch_workers_output = yes
对于大型应用,可以考虑使用多个PHP-FPM池来隔离不同类型的请求。
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
通过以上优化配置,可以显著提升LNMP架构中PHP-FPM的性能和稳定性。记得在调整配置后重启PHP-FPM服务以使更改生效。
sudo systemctl restart php7.4-fpm
请根据你的具体应用场景和服务器资源进行调整。