在 Ubuntu 上 PHP 变慢通常不是单一原因,而是环境、配置或代码层面叠加导致的。下面按最常见 → 较隐蔽的顺序给你系统排查思路。
很多人“感觉慢”,其实是模式用错。
✅ 检查:
php -v
php -m
Web 环境看:
ps aux | grep php-fpm
默认配置很保守。
配置文件:
/etc/php/8.x/fpm/pool.d/www.conf
重点参数:
pm = dynamic
pm.max_children = 5 # 太小!
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
✅ 建议(4 核 8G 示例):
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
重启:
systemctl restart php8.x-fpm
PHP 慢的 头号原因。
检查:
php -i | grep opcache
如果没有:
apt install php8.x-opcache
配置:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
PHP 里用到:
gethostbyname()mail()如果 DNS 慢,PHP 直接卡。
✅ 测试:
time nslookup example.com
✅ 解决:
127.0.0.1 代替 localhost/etc/resolv.conf 为稳定 DNS特别是:
检查:
iotop
df -h
✅ 优化:
session.save_handler = files
session.save_path = /dev/shm
display_errors = On
log_errors = On
error_log = /var/log/php_errors.log
✅ 生产环境:
display_errors = Off
php -m
太多模块 = 启动慢。
用:
xdebug
或:
blackfire
快速定位:
microtime(true);
php -v
php -i | grep opcache
ps aux | grep php-fpm
systemctl status php8.x-fpm
你可以直接贴:
php -i 关键部分我可以帮你逐行看配置并指出瓶颈。