华为云ECS服务器下Nginx反向代理502 Bad Gateway报错排查实战(SELinux与Keepalive配置)
在华为云ECS(CentOS/EulerOS)环境中配置Nginx反向代理后端服务(如Java SpringBoot、Node.js或Python应用)时,常遇到HTTP 502 Bad Gateway错误。本文记录一次真实的排障过程与解决方案。
一、问题现象
客户端请求通过华为云ECS上的Nginx反向代理访问后端服务时,Nginx返回 502 Bad Gateway。查看Nginx错误日志(/var/log/nginx/error.log):
[error] connect() failed (13: Permission denied) while connecting to upstream
或
[error] recv() failed (104: Connection reset by peer) while reading response header from upstream
二、常见原因分析与排查步骤
-
SELinux权限限制(Permission denied)
在RedHat/CentOS/EulerOS等系统中,SELinux默认对网络连接有限制,禁止Nginx发起向外的网络连接。
排查命令:
getsebool -a | grep httpd_can_network_connect
若显示 httpd_can_network_connect --> off,说明被SELinux拦截。
解决方案:
setsebool -P httpd_can_network_connect 1 -
Keepalive与上游连接复用超时问题(Connection reset by peer)
在Nginx与后端服务开启Keepalive长连接时,如果后端服务的超时时间小于Nginx的keepalive_timeout,后端先断开连接,Nginx继续复用旧连接就会导致502/104错误。
解决方案:
在Nginx upstream中设置:
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}
并在location块中包含:
proxy_http_version 1.1;
proxy_set_header Connection “”;
三、总结
在华为云ECS部署Nginx反向代理时,遇502错误优先排查:
- 检查 /var/log/nginx/error.log 中的报错类型;
- 权限报错关注 SELinux 设置(httpd_can_network_connect);
- 连接重置报错检查 Nginx 与 upstream 后端 Keepalive 参数配置。
- 点赞
- 收藏
- 关注作者
评论(0)