在Linux下优化PHP-FPM(FastCGI Process Manager)配置可以显著提升PHP应用程序的性能和稳定性。以下是一些关键的优化步骤和建议:
首先,确保你已经安装了PHP-FPM。你可以使用包管理器来安装,例如在Ubuntu上:
sudo apt update
sudo apt install php-fpm
PHP-FPM的主要配置文件通常位于 /etc/php/{version}/fpm/pool.d/www.conf
,其中 {version}
是你的PHP版本号。
/run/php/php{version}-fpm.sock
或 127.0.0.1:9000
。www-data
。dynamic
、ondemand
、static
。[www]
listen = /run/php/php{version}-fpm.sock
user = www-data
group = www-data
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
request_terminate_timeout = 30s
slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 10s
启用OPcache可以缓存编译后的PHP代码,从而减少服务器负载和提高性能。
opcache.enable = 1
opcache.enable_cli = 1
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 600
优化TCP/IP参数,如 tcp_fin_timeout
、tcp_tw_reuse
等。
sudo sysctl -w net.ipv4.tcp_fin_timeout=30
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
编辑 /etc/php/{version}/fpm/php.ini
文件进行PHP配置优化。
memory_limit = 256M
max_execution_time = 30
error_log = /var/log/php-fpm/error.log
启动PHP-FPM服务:
sudo systemctl start php{version}-fpm
sudo systemctl enable php{version}-fpm
监控PHP-FPM状态:
sudo systemctl status php{version}-fpm
如果你使用Nginx或Apache作为Web服务器,确保正确配置它们以使用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$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php{version}-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php{version}-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>
通过以上步骤,你可以有效地配置和优化PHP-FPM,从而提升你的PHP应用程序的性能。根据服务器的实际需求和负载情况,可以进一步调整上述参数以获得最佳性能。