nginx轮询需搭配被动健康检查与错误重试才能实现智能容错;必须显式配置max_fails、fail_timeout、proxy_next_upstream及超时参数,并明确列出500/502/503/504等状态码,避免误剔正常节点。

Nginx 默认轮询(round-robin)本身不感知后端健康状态,必须搭配被动健康检查与错误重试机制,才能在节点异常时自动跳过、快速恢复,避免请求打到已挂服务上造成超时或 502/504。
轮询模式下必须配置的熔断基础项
-
max_fails和fail_timeout要显式写在 upstream 的每个 server 行中,不能依赖默认值 -
proxy_next_upstream必须在 location 块中启用,且 HTTP 状态码要逐个列出 - 超时参数(
proxy_connect_timeout、proxy_read_timeout等)需合理收紧,防止连接堆积
让轮询真正“智能”的关键配置
- 每个后端 server 需单独设置容错:
server 192.168.1.10:8080 max_fails=1 fail_timeout=5s;
server 192.168.1.11:8080 max_fails=1 fail_timeout=5s;
小窗口 + 单次失败即摘除,实现秒级隔离 - 在 location 中启用错误转发:
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
注意:http_50x不生效,必须明确写出各状态码;error覆盖连接异常,timeout覆盖超时类失败 - 控制重试边界,防放大压力:
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
配合超时与降级提升稳定性
- 连接、发送、读取三类超时建议设为 3–5 秒区间,例如:
proxy_connect_timeout 3s;
proxy_send_timeout 5s;
proxy_read_timeout 5s; - 可加 backup server 做兜底:
server 127.0.0.1:8080 backup;
故障时自动切至本地静态页或降级接口
常见踩坑点提醒
- 后端返回 502/503 默认不计入
max_fails计数,没配proxy_next_upstream就等于没开熔断 -
fail_timeout是“暂停转发时长”,不是“故障持续时间”,5 秒后首个请求会试探性重连 - 不要给
http_404或http_401加入proxy_next_upstream,它们属于业务正常响应,加入会导致健康节点被误剔
不复杂但容易忽略











