Nginx 调试与排查指南:502 Bad Gateway、权限错误及配置验证
一、日志分析:快速定位核心问题
1. 502 Bad Gateway 日志分析
502 错误表示 Nginx 作为反向代理时无法从上游服务(如 PHP-FPM、Node.js、Tomcat)获取有效响应。
关键日志位置 :/var/log/nginx/error.log
常见日志模式:
bash
connect() failed (111: Connection refused) while connecting to upstream
upstream timed out (110: Connection timed out)
排查步骤:
-
检查上游服务状态 :确保 PHP-FPM、Node.js 等服务正在运行。
bashsystemctl status php-fpm ps aux | grep node
-
检查端口和网络连通性 :
bashnetstat -tulpn | grep :9000 # PHP-FPM 默认端口 telnet 127.0.0.1 9000 # 测试端口连通性
-
检查防火墙规则 :
bashiptables -L -n # 查看规则 ufw status # Ubuntu 防火墙
2. 权限错误日志分析
权限问题通常与文件、目录或进程所有者相关。
常见日志模式:
bash
Permission denied while reading upstream
open() "/var/www/html/index.php" failed (13: Permission denied)
排查步骤:
-
检查文件和目录权限 :
bashls -l /var/www/html # 查看文件权限 chmod -R 755 /var/www/html # 修复目录权限 chown -R www-data:www-data /var/www/html # 修复所有者
-
检查 SELinux/AppArmor :
bashgetenforce # 查看 SELinux 状态 setenforce 0 # 临时禁用 SELinux audit2why -a # 分析 SELinux 日志
二、配置验证与调试工具
1. nginx -t
验证配置语法
bash
nginx -t -c /etc/nginx/nginx.conf # 测试配置文件
# 输出示例:
# nginx: configuration file /etc/nginx/nginx.conf test is successful
常见配置错误:
- 缺少分号或括号不匹配
- 路径错误(如
root
或alias
配置错误) proxy_pass
指向无效地址(如http://localhost:3000
但服务未启动)
示例修复:
nginx
location / {
root /var/www/html; # 确保路径存在且可读
index index.php;
}
location /api {
proxy_pass http://127.0.0.1:3000; # 确保端口正确
proxy_set_header Host $host;
}
2. strace
跟踪进程行为
通过系统调用追踪定位深层问题(如文件访问、网络连接失败)。
使用场景:
- 调试 502 错误时,检查上游连接失败原因。
- 分析权限拒绝问题。
操作示例:
bash
# 跟踪 Nginx Worker 进程
ps aux | grep nginx # 获取 Worker 进程 PID
strace -p <PID> -s 1024 -e trace=file,network
# 或跟踪所有 Nginx 进程
strace -f $(pgrep nginx | sed 's/^/-p /') 2>&1 | grep 'ECONNREFUSED\|EPERM'
关键输出解析:
connect(3, {sa_family=AF_INET, sin_port=htons(9000), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 ECONNREFUSED
:上游服务未启动。open("/var/www/html/index.php", O_RDONLY) = -1 EACCES (Permission denied)
:文件权限不足。
三、场景化案例与解决方案
案例 1:PHP-FPM 未启动导致 502
现象 :访问 PHP 页面返回 502。
排查:
nginx -t
验证配置正常。- 检查
error.log
发现connect() failed (111: Connection refused)
。 systemctl start php-fpm
启动服务后问题解决。
案例 2:静态文件权限不足
现象 :CSS/JS 文件加载失败,日志显示 Permission denied
。
修复:
bash
chmod 644 /var/www/html/style.css
chown www-data:www-data /var/www/html
案例 3:上游服务响应超时
现象 :高并发时偶发 502,日志显示 upstream timed out
。
修复:调整 Nginx 超时配置:
nginx
location / {
proxy_pass http://backend;
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
}
案例 4:SELinux 阻止文件访问
现象 :权限配置正确但仍报错。
修复:
bash
chcon -Rt httpd_sys_content_t /var/www/html # 修改 SELinux 上下文
# 或临时禁用 SELinux
setenforce 0
案例 5:代理配置路径错误
错误配置:
nginx
location /api {
proxy_pass http://127.0.0.1:3000/; # 末尾斜杠导致路径被覆盖
}
现象 :访问 /api/users
代理到 http://127.0.0.1:3000/users
(期望 /api/users
)。
修复 :移除斜杠:proxy_pass http://127.0.0.1:3000;
。
四、综合调试流程图
rust
502 错误 -> 检查上游服务状态 -> 检查端口连通性 -> 调整超时配置 -> 检查资源限制
权限错误 -> 检查文件权限 -> 检查进程所有者 -> 禁用 SELinux/AppArmor -> 使用 strace 跟踪