Nginx自身不提供后端健康检查,但可通过upstream模块与location路由实现探针统一暴露:1. 独立server块直接响应;2. 业务server中优先拦截/healthz;3. 代理至专用健康聚合服务;需避免探针被错误转发或依赖不完整健康机制。

在 Nginx 中,server 块本身不直接提供后端健康检查功能(如自动剔除故障节点),但可以通过 配合 upstream 模块 + 自定义 location 路由 实现集群环境下的健康检查探针(如 /healthz)统一暴露和透传,同时避免将探针请求错误转发到后端服务——这是生产中常见且关键的配置需求。
1. 用独立 server 块暴露探针端点(推荐)
不依赖后端服务提供健康接口,而是由 Nginx 自身直接响应探针请求,最稳定、最低开销。适用于所有后端都正常才认为集群健康的情况。
- 监听一个专用端口(如
8080)或复用主端口但用不同 host/path - 使用
return 200 "OK\n";或add_header返回标准格式 - 不涉及 upstream,完全绕过后端,毫秒级响应
示例:
server {
listen 8080;
server_name _;
<pre class="brush:php;toolbar:false;">location /healthz {
return 200 "OK\n";
add_header Content-Type text/plain;
log_not_found off;
}
location / {
return 404;
}}
2. 在业务 server 块中拦截并处理探针路径
当必须复用业务端口(如 80 或 443)且探针路径需与业务共存时,在 server 块内优先匹配探针 location,阻止其进入 upstream 转发流程。
- 把
location /healthz放在所有proxy_pass规则之前(Nginx 按顺序匹配) - 可返回静态响应,也可透传给某个特定后端做聚合健康判断(见下一条)
- 务必加
log_not_found off;减少日志噪音
示例(直接响应):
server {
listen 80;
server_name example.com;
<pre class="brush:php;toolbar:false;">location /healthz {
return 200 '{"status":"healthy","checks":{}}';
add_header Content-Type application/json;
log_not_found off;
}
location / {
proxy_pass http://backend_cluster;
proxy_set_header Host $host;
# ... 其他代理配置
}}
3. 将探针路由到专用健康聚合服务(高级场景)
当需要真实探测多个后端状态(如检查数据库连接、缓存连通性、各实例 HTTP 健康端点),可部署一个轻量健康聚合服务(如用 Go/Python 写的 /healthz 接口),再由 Nginx 把探针请求定向过去。
- 定义一个仅用于健康检查的
upstream,指向该聚合服务 - 在业务
server块中用location /healthz显式proxy_pass到它 - 避免和业务 upstream 混用,防止健康检查流量干扰业务负载均衡
示例:
upstream health_checker {
server 10.0.1.100:8081; # 聚合服务地址
}
<p>server {
listen 80;
server_name example.com;</p><pre class="brush:php;toolbar:false;">location /healthz {
proxy_pass http://health_checker;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
log_not_found off;
}
location / {
proxy_pass http://backend_cluster;
# ...
}}
4. 注意事项与避坑点
- 不要把探针路径交给 upstream 默认转发:否则可能被轮询到宕机节点,导致探针失败误报
-
避免在 upstream 块中配置
health_check后仍让探针走业务路径:Nginx Plus 支持主动健康检查,但开源版需靠第三方模块(如nginx_upstream_check_module),且它只影响负载均衡决策,不替代应用层探针 - 确保探针响应头精简、无重定向、无认证:K8s liveness/readiness、Consul 等工具通常只认 2xx,且不跟随跳转、不处理 cookie 或 auth
-
使用
stub_status仅反映 Nginx 自身状态,不能代表后端集群健康,不可混用











