解决 Nginx 报错 upstream prematurely closed connection 502 修复
排查 Nginx 反向代理偶发 502 Bad Gateway 抛出 upstream prematurely closed connection,分析后端超时与长连接设置。
问题现象
客户端请求特定耗时接口时返回 502 Bad Gateway,Nginx 错误日志打印:
[error] 14210#14210: *3589 upstream prematurely closed connection while reading response header from upstream, client: 10.0.2.1, server: api.debug.wiki, request: "POST /api/v1/export HTTP/1.1", upstream: "http://127.0.0.1:3000/api/v1/export"
触发根因
- 后端应用因 OOM 或未捕获异常发生崩溃直接断开 Socket;
- 后端长连接 keepalive 超时短于 Nginx 端:后端先行 RST 连接;
- 后端处理时间超过了框架内部的最大超时限制(如 Node.js / Gunicorn / PHP-FPM)。
解决步骤
排查后端应用日志与系统 dmesg
确认后端是否触发 OOM Killer:
dmesg -T | grep -i oom
配置 Nginx upstream keepalive 连接池
在 upstream 块中添加长连接池以避免频繁握手被主动重置:
upstream backend_api {
server 127.0.0.1:3000;
keepalive 32;
}
server {
location / {
proxy_pass http://backend_api;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 120s;
}
}
验证确认
重载 Nginx 并发起大批量数据请求:
sudo nginx -t && sudo nginx -s reload
curl -X POST https://api.debug.wiki/api/v1/export
接口平稳返回 200 OK,502 报错彻底消除。


