在 Ubuntu 上 PHP-FPM 出现 504 Gateway Timeout,通常不是 PHP 本身报错,而是前端(Nginx/Apache)等待 PHP-FPM 处理超时。下面按常见原因和排查思路说明。
Client → Nginx → PHP-FPM → 超时未返回
Nginx 等了太久,PHP-FPM 没回应,于是返回 504 Gateway Timeout。
PHP 脚本执行超过限制:
php.inimax_execution_time = 30
request_terminate_timeout = 30s
✅ 解决:
max_execution_time = 300
request_terminate_timeout = 300s
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
include fastcgi_params;
fastcgi_read_timeout 30s; # 默认可能太小
}
✅ 建议:
fastcgi_read_timeout 300s;
proxy_read_timeout 300s;
请求太多,但:
pm = dynamic
pm.max_children = 5
导致请求排队,超时。
✅ 查看:
ps aux | grep php-fpm
✅ 调整:
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
Nginx 连不上 PHP-FPM:
systemctl status php8.1-fpm
日志:
/var/log/php8.1-fpm.log
/var/log/nginx/error.log
常见错误:
connect() to unix:/run/php/php8.1-fpm.sock failed (11: Resource temporarily unavailable)
✅ 解决:
systemctl restart php8.1-fpm
比如:
file_get_contents() 访问外部 API✅ 排查:
top
htop
# 1. 看 nginx 错误
tail -f /var/log/nginx/error.log
# 2. 看 php-fpm 状态
systemctl status php8.1-fpm
# 3. 看 php-fpm 日志
tail -f /var/log/php8.1-fpm.log
# 4. 看进程
ps aux | grep php-fpm
Nginx
fastcgi_read_timeout 300s;
PHP-FPM
request_terminate_timeout = 300s
php.ini
max_execution_time = 300
如果你愿意,可以贴:
我可以帮你精准定位是哪一层导致的 504。