核心是采集指标、存储聚合、可视化展示三步闭环:启用stub_status暴露基础指标,用nginx-prometheus-exporter转换为prometheus格式,prometheus抓取存储后通过grafana(如模板id12101)可视化关键指标。

用 Nginx 搭建静态资源响应的监控看板,核心是「采集指标 + 存储聚合 + 可视化展示」三步闭环。不依赖后端服务,纯靠 Nginx 自身状态与轻量 exporter 即可实现,适合中小流量静态站或内部资源服务的可观测性建设。
启用 Nginx 状态页(stub_status)
Nginx 必须开启 stub_status 模块才能对外暴露基础连接与请求指标。多数预编译包(如 yum/apt 安装的官方包)已内置该模块,验证方式:
- 执行
nginx -V 2>&1 | grep stub_status,输出含with-http_stub_status_module即已支持 - 在 server 块中添加 location 配置(建议限制访问 IP,避免暴露):
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.3.147; # 替换为 Prometheus 或 Exporter 所在机器 IP
deny all;
}
重载配置:nginx -s reload,访问 http://your_ip/nginx_status 应返回类似:
server accepts handled requests
120 120 240
Reading: 0 Writing: 1 Waiting: 2
部署 Nginx Exporter 采集指标
nginx-prometheus-exporter 是官方推荐的轻量采集器,它定期抓取 /nginx_status 页面并转换为 Prometheus 兼容的指标格式。
- 使用 Docker 一键运行(假设 Nginx 在宿主机 80 端口):
--name nginx-exporter \
-p 9113:9113 \
nginx/nginx-prometheus-exporter:latest \
--nginx.scrape-uri=http://host.docker.internal:80/nginx_status
注意:host.docker.internal 在 Linux 上需替换为宿主机真实 IP(如 172.17.0.1),或改用 --network host 模式直连 localhost。
- 验证采集是否就绪:访问
http://localhost:9113/metrics,应看到类似nginx_connections_active 3、nginx_http_requests_total等指标
接入 Prometheus 抓取并存储
修改 Prometheus 的 prometheus.yml,加入 job 抓取 Exporter:
- job_name: 'nginx'
static_configs:
- targets: ['localhost:9113']
重启 Prometheus 后,在 Web UI 的 Status > Targets 页面确认该 job 为 UP 状态,并在 Graph 中输入 nginx_http_requests_total 查看时间序列数据。
在 Grafana 中构建响应监控看板
导入现成模板可快速上手:
- 推荐使用 Grafana 官方 ID:
12101(Nginx Exporter Dashboard) - 关键指标建议关注:
– 每秒请求数(rate(nginx_http_requests_total[1m]))
– HTTP 状态码分布(sum by (code) (rate(nginx_http_requests_total[1m])))
– 活跃连接数与等待连接数趋势
– 请求平均响应时间(需配合 access_log + log exporter,stub_status 不提供)
若需更细粒度的静态资源响应分析(如某张图片加载慢、某个 JS 返回 404),需开启 Nginx access_log 并搭配 mtail 或 filebeat + Loki/Prometheus 做日志解析 —— 这属于进阶场景,stub_status 本身只提供汇总级指标。











