🆘 常见问题与排错
问题 1:502 Bad Gateway
**含义:**Nginx 作为反向代理,但后端服务没有响应。
bash
# 排查步骤:
# 1. 后端服务是否在运行?
systemctl status myapp
curl http://localhost:8080/health
# 2. 端口是否正确?
ss -tlnp | grep 8080
# 3. 查看 Nginx 错误日志
tail -50 /var/log/nginx/error.log
connect() failed (111: Connection refused) while connecting to upstream
# → 后端没启动
upstream prematurely closed connection while reading response header
# → 后端崩溃了
no live upstreams while connecting to upstream
# → 所有后端都挂了
# 4. SELinux 可能阻止 Nginx 连接后端
getenforce
setsebool -P httpd_can_network_connect 1问题 2:413 Request Entity Too Large
nginx
# 客户端上传文件超过 Nginx 限制
# 在 http/server/location 中增加:
client_max_body_size 100m; # 允许最大 100MB
# 如果用了 PHP,还要改 php.ini
# upload_max_filesize = 100M
# post_max_size = 100M问题 3:配置语法检查
bash
# 改完配置后先检查语法!
nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# 如果报错,根据提示修改。常见错误:
# - 每行末尾少了分号 ;
# - 括号不匹配
# - 引号没闭合
# 重载配置(不中断现有连接)
nginx -s reload
# 强制重新打开日志文件(日志切割后)
nginx -s reopen问题 4:访问日志分析
bash
# 查看访问最多的 IP(Top 10)
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
# 查看状态码分布
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
45231 200
3201 301
1523 404
892 500
234 502
# 查看最慢的请求(如果有 upstream_time)
awk '{print $NF, $7}' /var/log/nginx/access.log | sort -rn | head -10
# 实时监控请求速率
watch -n 1 'wc -l /var/log/nginx/access.log'