要让Nginx记录详细节点异常链路,需组合配置:启用debug级错误日志捕获重试细节;定义含$upstream_addr、$upstream_status等变量的自定义access日志格式;通过proxy_set_header透传并由后端回传X-Retry-Count实现重试计数;结合stub_status与error.log验证上游节点状态。

要让 Nginx 记录详细的节点异常链路(即哪次请求因哪个后端失败、重试了几次、最终由哪台服务器响应),关键不是开启某个“日志开关”,而是组合启用三类配置:精准的错误日志级别、带上下文的自定义日志格式、以及触发重试时能暴露后端行为的 proxy_next_upstream 配合 upstream 状态标记。
开启 debug 级别错误日志,捕获每次连接/重试细节
Nginx 默认 error_log 只记录严重错误,无法看到单次请求在多个后端间的流转过程。需临时提升日志级别到 debug(生产环境慎用,建议仅在排查期启用):
- 在 nginx.conf 的
http或server块中添加:error_log /var/log/nginx/error.log debug; - 该级别会输出类似这样的行:
[debug] ... *100000 upstream: "http://backend" failed (111: Connection refused) while connecting to upstream, server: example.com, request: "GET /api/v1/user HTTP/1.1", upstream: "192.168.1.10:8080", host: "example.com" - 注意:debug 日志量极大,排查完成后务必降回
error或warn级别
定义含后端地址与重试次数的自定义 access 日志格式
access log 不记录失败原因,但可记录最终成功响应的后端 IP 和重试计数。通过内置变量实现:
- 在
http块中定义新日志格式:log_format detailed '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$upstream_addr" "$upstream_status" "$upstream_response_time" "$upstream_http_x_retry_count"; - 其中:
$upstream_addr显示实际处理请求的后端地址(含端口),重试后会显示最终成功节点;$upstream_status对应该次响应的状态码;$upstream_response_time是该后端响应耗时;$upstream_http_x_retry_count需后端主动返回(见下条) - 在 location 中启用:
access_log /var/log/nginx/access_detailed.log detailed;
让后端配合返回重试次数标识(X-Retry-Count)
Nginx 本身不生成重试计数头,但可通过 proxy_set_header 向后端透传当前重试轮次,并要求后端在响应中回传:
- 在 location 中添加:
proxy_set_header X-Retry-Count $upstream_http_x_retry_count;
(首次请求该 header 为空,后端可设为 0) - 后端服务(如 Node.js/Java)收到请求后,解析
X-Retry-Count,加 1 后写入响应头:res.setHeader('X-Retry-Count', (parseInt(req.headers['x-retry-count'] || '0') + 1)); - Nginx 会自动将该响应头存入
$upstream_http_x_retry_count变量,供 access log 使用 - 这样日志中就能看到某次请求是第几次重试才成功的
结合 stub_status 和 upstream 模块状态验证节点剔除链路
要确认故障转移是否真正生效(比如某节点是否被 max_fails 标记为 down),不能只看日志,还要查实时状态:
- 启用 stub_status 模块(编译时默认包含):
location /nginx_status { stub_status; allow 127.0.0.1; deny all; } - 访问
curl http://localhost/nginx_status,输出中Active connections下的Reading/Writing/Waiting可反映当前活跃连接分布 - 更关键的是查看 upstream 状态:Nginx 开源版无原生接口,但可通过以下方式间接验证:
— 查看 error.log 中是否有upstream server temporarily disabled记录
— 手动执行curl -I http://target_backend_ip:port模拟探测,比对 upstream 中配置的fail_timeout是否吻合


















