ubuntu nginx故障排查技巧
小樊
42
2026-01-01 17:11:17
Ubuntu 下 Nginx 故障排查技巧
一 快速定位流程
- 验证配置语法:执行sudo nginx -t,确保输出为syntax is ok / test is successful;若有错误,按提示行号修正后再继续。
- 查看服务状态与启动日志:执行sudo systemctl status nginx,必要时用journalctl -xe查看详细错误。
- 实时跟踪错误日志:执行sudo tail -f /var/log/nginx/error.log,优先从最新报错入手。
- 端口与连通性:用**ss -tulnp | grep ':80|:443’或netstat -tulnp | grep ':80|:443’确认端口占用;用curl -I http://127.0.0.1/**或本机外网地址测试访问。
- 防火墙放行:Ubuntu 常用sudo ufw allow 80,443/tcp放行端口。
- 变更生效:语法无误后执行sudo systemctl reload nginx(或 restart)。
二 常见症状与对策
- 无法启动或重启失败
- 典型日志:bind() to 0.0.0.0:80 failed (98: Address already in use)。
- 处理:查占用进程ss -tulnp | grep :80,结束冲突进程或调整 Nginx 监听端口;若端口被Apache/其他服务占用,先停占用者或改用8080/8443等端口。
- 403 Forbidden
- 典型日志:open() “/var/www/html/index.html” failed (13: Permission denied)。
- 处理:确认网站目录对 Nginx 运行用户(常见为www-data)可读可执行;示例:
- 权限:sudo chmod -R 755 /var/www/html && sudo chmod 644 /var/www/html/index.html
- 属主:sudo chown -R www-data:www-data /var/www/html
- 502 Bad Gateway
- 含义:Nginx 能连上游,但上游返回无效响应或异常关闭。
- 快速检查:
- 上游存活:systemctl 检查 PHP-FPM/Node/Tomcat;端口监听ss -tlnp | grep 9000(PHP-FPM)或grep 8080。
- 连通性:本机telnet 127.0.0.1 9000或curl http://127.0.0.1:9000/status。
- 日志关键词:connect() failed (111: Connection refused)、recv() failed (104: Connection reset by peer)、upstream prematurely closed connection。
- 504 Gateway Timeout
- 含义:上游处理太慢,超过 Nginx 超时阈值。
- 处理:适当增大超时(示例):
- proxy_connect_timeout 60s; proxy_read_timeout 60s; proxy_send_timeout 60s;
- FastCGI 场景:fastcgi_read_timeout 60s;
- 400/413/499 等客户端错误
- 400:请求头过大,适当增大client_header_buffer_size / large_client_header_buffers。
- 413:请求体过大,设置client_max_body_size 10m;并与 PHP 的post_max_size / upload_max_filesize匹配。
- 499:客户端提前关闭连接,多为业务超时或前端取消,结合request_time与上游耗时排查。
三 日志与关键线索
- 错误日志位置:默认**/var/log/nginx/error.log**;访问日志:/var/log/nginx/access.log。建议为关键server段单独定义access_log / error_log,便于隔离问题。
- 高价值字段(在 access.log 中常用):$status、$upstream_status、$request_time、$upstream_response_time、$http_host、$remote_addr,可快速判断是 Nginx 本身还是上游瓶颈。
- 典型错误模式与含义:
- no live upstreams while connecting to upstream:所有上游均不可用(瞬时故障或进程池耗尽)。
- upstream sent invalid header:上游响应头不合规,检查后端输出或协议(如启用proxy_http_version 1.1)。
- SSL_do_handshake() failed:SSL 握手失败,检查证书链、域名匹配、TLS 版本与密码套件。
四 进阶调试与优化
- 运行时诊断
- 进程跟踪:获取 Worker PID 后执行strace -p -s 1024 -e trace=file,network,定位文件访问被拒或连接被拒等系统调用问题。
- 上游健康页:为 PHP-FPM 开启状态页(如**/php-fpm-status**),配合**allow 127.0.0.1; deny all;**查看进程繁忙度、最大子进程数是否触顶。
- 配置与架构优化
- 超时分层设置:区分连接、发送、读取阶段,避免一刀切;高延迟/大文件上传场景适当上调。
- 进程与连接:结合worker_processes / worker_connections与系统ulimit -n,避免文件描述符与连接数瓶颈。
- 安全与合规:谨慎使用root运行 Nginx;上传目录禁止脚本执行;启用security headers与合适的TLS配置。