Nginx 反向代理报错 upstream timed out (110: Connection timed out) 排障
Nginx 返回 504 Gateway Time-out 且日志记录 upstream timed out (110: Connection timed out)。本文深入剖析 TCP 握手丢包、内网防火墙拦截与 proxy_connect_timeout 调优实战。
在微服务架构中使用 Nginx 作为负载均衡反向代理时,前端客户端在调用接口时偶发或持续收到 504 Gateway Time-out。查看 Nginx 的错误日志 /var/log/nginx/error.log,出现大面积警告:[error] 1234#1234: *567 upstream timed out (110: Connection timed out) while connecting to upstream, client: 192.168.1.50, server: api.example.com, request: "POST /order HTTP/1.1", upstream: "http://10.244.3.40:8080/order"。
故障现象与日志
Nginx 错误日志显示:
2026/01/01 10:00:00 [error] 1234#1234: *890 upstream timed out (110: Connection timed out) while connecting to upstream, client: 10.0.0.1, server: api.example.com, request: "POST /api/v1/trade HTTP/1.1", upstream: "http://192.168.2.15:8080/api/v1/trade", host: "api.example.com"
注意报错中的核心短语是 while connecting to upstream(在连接上游时超时),且错误码为 110: Connection timed out。这表明:Nginx 与后端上游在进行最初始的 TCP 三次握手阶段就发生了彻底超时,甚至连 SYN+ACK 报文都未收到。
根本原因剖析
- 中间网络防火墙或安全组屏蔽了通信端口(最主要原因):
后端真实服务器的本地防火墙(如
ufw、firewalld、iptables)或云厂商私有网络安全组未对 Nginx 节点的内网 IP 放通 8080 端口。由于防火墙通常采用DROP(直接静默丢弃)策略,Nginx 发送 SYN 报文后收不到任何回应,一直阻塞等待直至超时。 - 上游服务 Pod 已经死亡或 IP 发生漂移:在 Kubernetes 环境中,目标 Pod 已经销毁,但 Nginx upstream 配置中写死了静态 IP,导致 Nginx 持续向一个物理上不存在的黑洞 IP 发送 TCP 握手。
- proxy_connect_timeout 配置过短:在复杂的跨机房专线或跨 VPC 通信中,网络偶有轻度拥塞,若
proxy_connect_timeout仅配置为 1 秒或 2 秒,轻微抖动即被判定为超时。 - 后端服务器的 TCP 半连接队列(SYN Queue)完全打满:后端服务负载过载,操作系统内核直接丢弃新的 SYN 包。
诊断排查步骤
- 在 Nginx 宿主机直接测试到上游 IP 和端口的连通性:
# 测试 TCP 握手连通性与耗时
nc -zv -w 5 192.168.2.15 8080
如果命令挂起整整 5 秒后提示超时,说明 100% 是网络路由或防火墙拦截问题。
- 检查上游目标服务器的防火墙拦截规则:
登录上游机器
192.168.2.15:
iptables -L -n -v | grep 8080
- 使用 tcpdump 在上游机器抓取 Nginx 发来的 SYN 包:
tcpdump -i any -nn "src host <nginx-ip> and port 8080"
观察上游是否收到了 SYN 包,以及是否回应了 SYN-ACK。
解决方案与恢复操作
步骤一:放通内网防火墙与安全组策略
在后端目标服务器上放通对应端口对 Nginx 的访问:
在 ufw(Ubuntu)下:
sudo ufw allow from <nginx-ip> to any port 8080 proto tcp
在 firewalld(CentOS / RHEL)下:
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="<nginx-ip>" port port="8080" protocol="tcp" accept'
sudo firewall-cmd --reload
步骤二:合理调优 Nginx 的连接超时与容错重试
在 nginx.conf 中为 upstream 配置合理的连接超时时间与故障重试转移:
upstream backend_pool {
server 192.168.2.15:8080 max_fails=2 fail_timeout=10s;
server 192.168.2.16:8080 max_fails=2 fail_timeout=10s;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend_pool;
# 调大建连超时时间(默认为 60s,内网建议配置为 5s~10s 以便快速故障倒换)
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
# 当一个后端连不上时,立即自动切换到下一个节点,客户端无感
proxy_next_upstream error timeout invalid_header http_502 http_504;
proxy_next_upstream_tries 3;
}
}
重新加载生效:
nginx -t && nginx -s reload
步骤三:在 Kubernetes 中避免在 Nginx 写死静态 Pod IP
在容器云环境中,Nginx 应当通过 Service 域名或 Ingress 动态解析上游地址,严禁将生命周期短暂的 Pod IP 写入静态配置文件。


