nginx需通过prometheus+alertmanager+pagerduty实现告警:1.用nginx-prometheus-exporter采集指标并配置prometheus抓取;2.alertmanager配置pagerduty集成密钥;3.prometheus定义5xx错误率、连接数超限等规则;4.pagerduty中设置人员联系方式与升级策略。

Nginx 本身不内置告警能力,需借助外部监控系统(如 Prometheus + Alertmanager)采集指标并触发 PagerDuty 告警;电话与短信通知由 PagerDuty 自动分发,前提是运维人员在 PagerDuty 中正确配置了联系方式和通知策略。
1. 通过 Prometheus + Exporter 采集 Nginx 指标
让 Nginx 暴露可被监控的指标是第一步。推荐使用 nginx-prometheus-exporter(官方维护):
- 在 Nginx 服务器上部署 exporter(如 Docker 运行:
docker run -d -p 9113:9113 --name nginx-exporter -v /etc/nginx:/etc/nginx:ro nginx/nginx-prometheus-exporter) - 确保 Nginx 开启
stub_status(或使用ngx_http_api_module,新版更推荐),exporter 依赖该接口获取连接数、请求速率等基础指标 - 在 Prometheus 的
scrape_configs中添加 job,抓取 exporter 的http://<nginx-host>:9113/metrics</nginx-host>
2. 在 Alertmanager 中配置 PagerDuty 告警路由
Alertmanager 是实际执行告警分发的核心组件,需对接 PagerDuty 的 Integration Key:
- 在 PagerDuty 后台创建一个 Service → 选择集成类型为 Prometheus → 复制生成的 Integration Key
- 修改 Alertmanager 配置文件
alertmanager.yml,添加pagerduty_configs:
route:
receiver: 'pagerduty'
receivers:
- name: 'pagerduty'
pagerduty_configs:
- service_key: 'your-integration-key-here'
description: '{{ .CommonLabels.alertname }}: {{ .CommonAnnotations.summary }}'
details:
instance: '{{ .CommonLabels.instance }}'
severity: '{{ .CommonLabels.severity }}'
重启 Alertmanager 生效。
3. 设置 Nginx 关键告警规则(prometheus.rules)
在 Prometheus 中定义何时触发告警,例如高错误率、连接超限、服务不可达:
- 5xx 错误率持续 2 分钟 > 5%:
100 * sum(rate(nginx_http_requests_total{code=~"5.."}[2m])) / sum(rate(nginx_http_requests_total[2m])) > 5 - 活跃连接数超过阈值(如 1000):
nginx_connections_active > 1000 - Nginx 进程不可用(exporter 抓取失败):
absent(nginx_up) == 1
将规则加载进 Prometheus,并确保 rule_files 已配置。
4. 在 PagerDuty 中配置人员通知策略
告警能否电话/短信触达,完全取决于 PagerDuty 的用户设置:
- 每个运维人员需在个人资料中填写真实手机号,并启用 SMS 和 Phone 通知方式
- 创建 Escalation Policy,指定谁在什么时间、以何种方式(如立即电话 → 5 分钟后短信 → 转交备岗)响应告警
- 将该策略绑定到前述的 Prometheus Service 上
- 可选:开启 Priority 或 Incident Urgency,对 P1 级 Nginx 全站故障自动触发强提醒
完成以上步骤后,当 Nginx 触发告警规则,Prometheus 推送至 Alertmanager,再经 PagerDuty 按策略拨打值班人员电话或发送短信,整个链路即跑通。











