Nginx通过upstream_check_module实现后端节点故障时的平滑自动下线:需编译启用该模块,配置interval、rise、fall等健康检查参数,并配合proxy_next_upstream提升请求级容错,最后通过/status页面实时监控节点状态。

在 Nginx 中实现后端节点故障时的平滑自动下线,核心在于结合 upstream_check_module(即 Upstream-Check 模块)与内置的健康检查机制,让 Nginx 主动探测后端状态,并在异常时临时剔除节点,而不依赖被动失败重试或手动干预。
确认 Nginx 已编译支持 upstream_check_module
Upstream-Check 并非 Nginx 官方模块,需额外编译。主流发行版的预编译包(如 apt/yum 安装的 nginx)通常不包含它。验证方式:
- 执行
nginx -V 2>&1 | grep -o with-http_upstream_check_module,有输出说明已启用; - 若无,需下载对应版本的 nginx_upstream_check_module 补丁,重新编译 Nginx;
- 注意补丁版本需与 Nginx 版本严格匹配(例如 nginx 1.20.x 对应 check module 的 v0.3.0 分支)。
配置带健康检查的 upstream 块
在 http 或 stream 上下文中定义 upstream,并启用检查参数:
upstream backend_cluster {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
check interval=3 rise=2 fall=3 timeout=1 type=http;
check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
关键参数说明:
-
interval=3:每 3 秒探测一次; -
rise=2:连续 2 次成功则标记为“恢复上线”; -
fall=3:连续 3 次失败则标记为“宕机”,自动从负载均衡池中剔除; -
type=http:使用 HTTP 协议探测(也支持 tcp、ssl_hello、mysql 等); -
check_http_send发送自定义探测请求,建议用轻量级 HEAD 请求; -
check_http_expect_alive定义哪些响应码视为健康(如仅接受 2xx/3xx)。
配合 proxy_next_upstream 实现请求级容错
Upstream-Check 负责“节点级”上下线,但单次请求仍可能在检测间隙打到刚失联的节点。需补充以下配置提升健壮性:
location / {
proxy_pass http://backend_cluster;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 3s;
}
这样当某次请求遇到网络错误或后端返回 5xx,Nginx 会自动尝试下一个可用节点,用户无感知。
查看和验证健康状态
启用模块后,可通过内置状态页实时观察节点状态:
location /status {
check_status;
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
}
访问 http://your-nginx-ip/status 可看到各节点的 IP、端口、状态(up/down)、失败次数、检查间隔等。模拟某台后端关闭后,该页面会很快显示其状态变为 down,且后续流量不再分发过去。











