Nginx提供了多种方式来配置HTTP服务的健康检查,以确保后端服务的可用性。以下是几种常见的配置方法:
Nginx默认会进行被动健康检查,当请求失败时会标记服务器为不可用。
upstream backend {
server backend1.example.com;
server backend2.example.com;
# 被动健康检查参数
max_fails=3; # 允许的最大失败次数
fail_timeout=30s; # 服务器被标记为不可用的时间
}
Nginx Plus和开源Nginx(需要ngx_http_upstream_module)支持主动健康检查:
upstream backend {
zone backend 64k;
server backend1.example.com;
server backend2.example.com;
# 健康检查配置
health_check interval=5s fails=3 passes=2 uri=/health;
health_check_timeout 3s;
}
对于开源Nginx,可以使用ngx_http_upstream_check_module
模块:
upstream backend {
server backend1.example.com;
server backend2.example.com;
check interval=3000 rise=2 fall=5 timeout=1000 type=http;
check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
在后端服务中添加专门的健康检查端点:
location = /health {
access_log off;
allow 127.0.0.1;
deny all;
# 检查数据库连接等
# 返回200表示健康,其他表示不健康
return 200;
}
Nginx Plus提供了更丰富的健康检查功能:
upstream backend {
zone backend 64k;
server backend1.example.com slow_start=30s;
server backend2.example.com;
# 高级健康检查
health_check interval=5s
uri=/custom/health
match=statusok
port=8080;
}
match statusok {
status 200;
header Content-Type = text/html;
body ~ "Server OK";
}
以上配置可以根据您的具体需求进行调整,确保后端服务的可用性监控既有效又不会对系统性能造成过大影响。