在Ubuntu上优化PHP-FPM(FastCGI Process Manager)的响应时间,可以通过以下几个步骤来实现:
编辑PHP-FPM的配置文件,通常位于/etc/php/7.x/fpm/pool.d/www.conf
(根据你的PHP版本可能会有所不同)。
sudo nano /etc/php/7.x/fpm/pool.d/www.conf
pm
:选择进程管理方式,推荐使用dynamic
或ondemand
。pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
request_terminate_timeout
:设置请求超时时间,防止长时间运行的脚本。request_terminate_timeout = 30s
slowlog_timeout
:设置慢查询日志的超时时间。slowlog_timeout = 0
编辑PHP的配置文件,通常位于/etc/php/7.x/cli/php.ini
或/etc/php/7.x/apache2/php.ini
。
sudo nano /etc/php/7.x/cli/php.ini
memory_limit
:根据需要调整内存限制。memory_limit = 128M
max_execution_time
:设置脚本的最大执行时间。max_execution_time = 30
opcache.enable
:启用OPcache以提高性能。opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
确保OPcache已启用并正确配置。OPcache可以显著提高PHP脚本的执行速度。
如果你使用的是Nginx或Apache作为Web服务器,也需要相应地调整它们的配置。
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/php7.x-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/php7.x-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>
使用工具如top
、htop
、php-fpm status
等来监控系统资源的使用情况,并根据实际情况进一步调优。
定期重启PHP-FPM和Web服务器服务以应用配置更改。
sudo systemctl restart php7.x-fpm
sudo systemctl restart nginx # 或 apache2
通过以上步骤,你应该能够显著优化Ubuntu上PHP-FPM的响应时间。记得在每次更改配置后都要进行测试,以确保系统的稳定性和性能。