解决 Nginx 报错 502 Bad Gateway 104 Connection reset
分析 Nginx 反向代理收到 502 并在日志中记录 recv() failed (104: Connection reset by peer) 的后端服务崩溃与超时根因及修复方案。
问题现象
用户请求服务时返回 502 Bad Gateway,Nginx error.log 日志记录:
2026/11/15 15:00:00 [error] 1234#1234: *567 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 10.0.0.1, server: api.example.com, request: "POST /api/process HTTP/1.1", upstream: "http://127.0.0.1:8000/api/process", host: "api.example.com"
触发根因
- 上游后端业务进程(如 PHP-FPM、Node.js、Python Gunicorn、Java JVM)在生成 HTTP 响应头期间发生致命崩溃(如段错误、OOM 内存超限被杀、未捕获 Panic),操作系统内核向上游对端发送了 TCP RST 包。
- PHP-FPM 的
max_execution_time或 worker 内存上限触发,master 进程强行 kill 了该 worker。 - 后端服务 Keep-Alive 连接在空闲超时临界点主动关闭了套接字。
解决步骤与操作命令
步骤一:查看后端进程的真实错误日志与系统 dmesg
检查是否有 OOM 强杀或代码 Panic:
sudo dmesg -T | grep -E -i "oom|killed"
sudo tail -n 100 /var/log/php-fpm.log # 或后端应用日志
步骤二:调大后端超时与工作进程内存上限(以 PHP-FPM 为例)
编辑 www.conf:
request_terminate_timeout = 120s
php_admin_value[memory_limit] = 512M
步骤三:配置 Nginx 向上游发送 Keep-Alive 心跳避免竞态断开
在 Nginx upstream 块中配置长连接保持:
upstream backend_cluster {
server 127.0.0.1:8000;
keepalive 32; # 保持长连接池
}
server {
location / {
proxy_pass http://backend_cluster;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
验证确认
重新发起压测调用: 后端平稳处理请求并返回合法 HTTP 头部,Nginx 正常转发 HTTP 200,104 Connection reset 错误彻底消除。


