要实现nginx连接数实时监控,需三步:启用stub_status并限制访问;用nginx-exporter或lua将其转为prometheus格式;配置prometheus抓取并告警,在grafana可视化。

要实现 Nginx 连接数的实时监控,核心是让 Prometheus 能持续采集 stub_status 暴露的指标。这需要三步打通:Nginx 正确开启并暴露 stub_status、用 exporter 或反向代理将其转为 Prometheus 可读格式、Prometheus 抓取并存储数据,最后在 Grafana 展示。
确保 Nginx 已启用 stub_status 并可被访问
stub_status 不是默认开启的模块,需确认编译时已包含(主流发行版通常内置),并在 server 或 location 块中显式配置:
- 在 Nginx 配置中添加如下片段(建议放在 default_server 或独立 location):
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本地或监控节点访问
deny all;
}
重载 Nginx 后,执行 curl http://127.0.0.1/nginx-status 应返回类似:
server accepts handled requests
12345 12345 67890
Reading: 0 Writing: 3 Waiting: 9
注意:不能用 HTTPS 直接暴露该接口,除非你有证书且明确信任;生产环境务必限制 IP 访问,避免敏感指标泄露。
将 stub_status 输出转换为 Prometheus 格式
Prometheus 无法直接解析 stub_status 的纯文本,需中间层转换。推荐两种轻量方案:
-
使用 nginx-exporter(推荐):官方维护的 nginx-prometheus-exporter,它主动轮询 stub_status 接口,将字段映射为标准指标(如
nginx_connections_active、nginx_connections_waiting)。启动命令示例:
-nginx.scrape-uri http://127.0.0.1/nginx-status
默认监听 :9113/metrics,Prometheus 可直接抓取。
- 用 Nginx 自身做简单转换(零依赖):如果不想额外部署进程,可在 Nginx 中用 Lua 模块(需编译 lua-nginx-module)写一个 /metrics location,解析 stub_status 响应并输出 Prometheus 文本格式。适合已有 Lua 环境的场景,但维护成本略高。
配置 Prometheus 抓取并定义告警规则
在 prometheus.yml 的 scrape_configs 中添加 job:
static_configs:
- targets: ['localhost:9113']
重启 Prometheus 后,访问 http://<prometheus>:9090/targets</prometheus> 确认状态为 UP。常用连接类指标包括:
-
nginx_connections_active:当前活跃连接数(ESTABLISHED) -
nginx_connections_waiting:处于 keepalive 等待状态的连接数 -
nginx_connections_accepted_total:累计接受连接数(可用于计算每秒新建连接)
典型告警规则示例(放入 alert.rules):
- name: nginx-alerts
rules:
- alert: NginxHighActiveConnections
expr: nginx_connections_active > 1000
for: 2m
labels:
severity: warning
annotations:
summary: "Nginx active connections too high"
在 Grafana 中可视化关键连接趋势
导入社区 Nginx Dashboard(ID:10173 或 12123),或新建面板手动输入查询:
- 总活跃连接趋势:
nginx_connections_active - 等待连接占比:
nginx_connections_waiting / nginx_connections_active - 每秒新建连接:
rate(nginx_connections_accepted_total[1m])
建议叠加 HTTP 状态码(如 5xx)、upstream response time,便于关联分析——比如 waiting 骤增 + 502 上升,可能指向后端异常或超时配置不合理。










