nginx 本身不内置告警能力,需依赖外部监控系统;可通过错误日志、健康端点、prometheus 指标等方式暴露故障信号,再由 prometheus+alertmanager、zabbix 或自建脚本等工具捕获并触发告警。

Nginx 本身不内置告警能力,故障转移靠 upstream 和 proxy_next_upstream 实现自动切换,但“主动通知”需外部系统配合。真正的告警必须由独立监控工具触发,Nginx 只负责暴露可观测指标或日志线索。
让 Nginx 暴露故障信号供监控采集
要让告警系统知道节点是否失效,关键是让 Nginx 输出可被识别的健康状态信息:
-
启用详细错误日志:在
http或location块中设置error_log /var/log/nginx/backend_error.log warn;,确保max_fails触发下线、proxy_next_upstream发起重试等行为被记录为warn级别日志 -
暴露自定义健康端点:用
location = /healthz返回简单状态,例如检查 upstream 中可用节点数(需配合 OpenResty 或 nginx-plus 的upstream_conf模块);开源版可退而求其次——写一个轻量脚本定期curl -I http://127.0.0.1:8080/healthz并解析响应头中的X-Upstream-Status(需后端配合注入) -
导出 Prometheus 指标:使用
nginx-module-vts(开源)或nginx-plus内置的/api接口,获取upstream.fails、upstream.down等实时计数,这是告警最可靠的数据源
用监控工具捕获异常并触发告警
日志或指标只是数据,告警靠外部系统判断和通知:
-
Prometheus + Alertmanager:配置 Prometheus 抓取 Nginx 指标,写规则如
sum(nginx_upstream_fails_total{upstream="backend"}) > 5或count(nginx_upstream_down{upstream="backend"} == 1) > 0,命中即通过 Email、Webhook(钉钉/企微)、PagerDuty 推送 -
Zabbix/Filebeat + ELK:用 Filebeat 收集 Nginx error log 中含
"upstream failed"或"no live upstreams"的 warn 日志行,Zabbix 监控日志关键词频次,ELK 则做聚合分析与可视化告警 -
自建脚本轮询检测:每 10 秒执行一次
curl -s -o /dev/null -w "%{http_code}" http://localhost/healthz,返回非 200 就调用curl -X POST https://oapi.dingtalk.com/... -d '{"text":"Nginx 后端集群异常"}'发钉钉
关键配置示例(确保信号可采)
在 http 块中加入:
log_format upstream_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'upstream_addr:$upstream_addr '
'upstream_status:$upstream_status '
'upstream_response_time:$upstream_response_time';
<p>server {
location = /healthz {
return 200 "ok\n";
add_header Content-Type text/plain;
}
}</p><p>upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup;
}
</p>
再在对应 location 中启用 access_log /var/log/nginx/upstream_access.log upstream_log;,这样每次重试、换节点都会留下明确痕迹。
为什么不能只靠 Nginx 自己发告警
Nginx 是无状态转发器,设计上不支持外连网络、调用 API 或发送邮件。它的角色是快速响应请求、隔离故障、维持服务连续性。把告警逻辑塞进 Nginx 不仅违背职责分离原则,还会因阻塞 I/O 影响性能,甚至引发级联失败。生产环境务必让监控系统承担通知职责,Nginx 只专注做好“能转就转,转不了就换”的本职。











