健康检查与故障转移
健康检查是负载均衡的核心功能。通过检测后端状态,NGINX 可自动摘除故障节点并在恢复后重新加入。
被动健康检查
基于请求的检查
nginx
upstream backend {
server 10.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.2:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.3:8080 max_fails=2 fail_timeout=20s;
}
max_fails— 在fail_timeout内连续失败的最大次数fail_timeout— 失败后的隔离时间,也是重新检查周期- 达到
max_fails后服务器标记为不可用
被动检查仅在处理请求时发现故障。空闲服务器可能长时间不会被检测到。
故障转移条件
nginx
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 10s;
}
error— 连接后端失败timeout— 与后端通信超时http_500等 — 特定响应码proxy_next_upstream_tries— 最大重试次数(0 不限制)
主动健康检查
NGINX Plus 主动检查
nginx
upstream backend {
zone backend 64k;
server 10.0.0.1:8080;
server 10.0.0.2:8080;
health_check interval=10s fails=3 passes=2 uri=/health match=http_200_302;
}
match http_200_302 {
status 200-302;
header Content-Type = text/html;
body ~ "OK";
}
interval— 检查间隔fails— 连续失败次数后标记不可用passes— 连续成功次数后重新加入match— 定义健康响应的匹配规则
主动检查定期发送探测请求,即使没有用户流量也能检测后端状态。仅 NGINX Plus 提供。
开源版主动检查替代
nginx
# 使用第三方模块 nginx_upstream_check
upstream backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
check interval=5000 rise=2 fall=3 timeout=3000 type=http;
check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
nginx_upstream_check是淘宝开发的开源模块,为社区版 NGINX 提供主动健康检查。
优雅下线
维护模式
nginx
upstream backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080 down; # 标记下线维护
server 10.0.0.3:8080 backup;
}
设置
down标记后 NGINX 不再分发流量到此服务器。配合 Keepalived 或 CI/CD 流程实现优雅下线。
慢启动(NGINX Plus)
nginx
upstream backend {
server 10.0.0.1:8080 slow_start=30s;
server 10.0.0.2:8080 slow_start=30s;
}
后端恢复后逐步增加流量,避免瞬间过载。仅 Plus 版支持。
监控集成
查看上游状态
nginx
# NGINX Plus API
location /upstream_conf {
allow 10.0.0.0/8;
deny all;
proxy_pass http://127.0.0.1:8080/api/6/http/upstreams;
}
NGINX Plus 提供 REST API 查看和管理 upstream 状态。开源版需使用
stub_status模块或第三方工具。
要点总结
- 被动检查通过
max_fails和fail_timeout检测故障 proxy_next_upstream定义当前请求的故障转移行为- 主动检查定期发送探测请求,发现故障更快
- 开源版使用
nginx_upstream_check模块实现主动检查 down标记用于手动维护下线- 慢启动防止后端恢复后瞬间过载
- 结合被动和主动检查实现完整的故障转移机制
📝 发现内容有误?点击此处直接编辑