DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Nginx 报错 upstream timed out 110: Connection timed out

分析 Nginx 代理上游报 upstream timed out 110 Connection timed out 根因,详解 fastcgi/proxy 连接超时与进程排队调优步骤。

问题现象

通过 Nginx 访问后端服务(如 PHP-FPM、Gunicorn 或 Tomcat)时页面响应极为缓慢最终返回 HTTP 504 Gateway Time-out,查看 Nginx error.log:

2026/11/15 10:15:00 [error] 19283#0: *12053 upstream timed out (110: Connection timed out) while connecting to upstream, client: 192.168.1.100, server: example.com, request: "GET /index.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000"

触发根因

  1. 后端工作进程池被完全占满且 backlog 队列溢出:PHP-FPM 或应用服务器的 pm.max_children 达到上限,新请求在 TCP listen backlog 中排队,超过 Nginx 的连接建立超时时间。
  2. 后端服务监听了错误的地址或端口未开放:后端仅监听在 Unix Socket 或特定私网 IP 上,但 Nginx 配置了 127.0.0.1:9000。
  3. 防火墙阻断了 TCP SYN 握手包。

诊断排查步骤

  1. 检查后端进程监听状态与排队队列:
ss -tulpn | grep 9000

观察 Send-Q 与 Recv-Q。若 Recv-Q 大于 0 说明连接正在积压排队。

  1. 检查 PHP-FPM 状态页或活跃进程数:
ps aux | grep php-fpm | grep -v master | wc -l

解决步骤与操作命令

步骤一:扩容后端进程池容量与监听队列

编辑 /etc/php/8.1/fpm/pool.d/www.conf:

; 调大工作进程数以吸收并发
pm = dynamic
pm.max_children = 150
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 1000

; 调大 TCP 监听队列
listen.backlog = 1024

重启 PHP-FPM 生效:

systemctl restart php8.1-fpm

步骤二:采用 Unix Domain Socket 替代 TCP 握手(单机极速通信)

单机环境下 Unix Socket 性能优于 TCP 网络栈且开销更小: 在 PHP-FPM 中配置:

listen = /run/php/php-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

在 Nginx 中配置:

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;
    include fastcgi_params;
    fastcgi_connect_timeout 10s;
    fastcgi_read_timeout 60s;
}

步骤三:适度调整 Nginx 连接与读取超时

在 nginx.conf 中合理增加缓冲宽限期:

fastcgi_connect_timeout 15s;
proxy_connect_timeout 15s;

验证方法

重新加载 Nginx 服务:

systemctl reload nginx

发起并发测试请求: 页面在数百毫秒内平稳渲染完成,Nginx 错误日志中不再输出 110: Connection timed out 报错。