nginx_exporter:Prometheus 监控 Nginx 基础指标

原文:https://github.com/discordianfish/nginx_exporter(discordianfish 维护)
说明:安装方式和配置参数以官方仓库为准。源码细节请参考 GitHub 仓库。
备选方案:如果需要更丰富的 Nginx 指标,可以看 nginx-vts-exporter 或 Nginx 官方出的 nginx-prometheus-exporter


项目简介

这是一个轻量级的 Nginx Prometheus Exporter,核心功能就是采集 Nginx 状态页面(nginx_status)的数据,然后转成 Prometheus 格式暴露出来。

它做的事情很简单:

  1. 定期从 Nginx 的 stub_status 页面抓取基础统计
  2. 把数据转成 Prometheus 指标的格式
  3. 9113 端口通过 /metrics 暴露

前置:开启 Nginx stub_status

在 Nginx 配置里加一个 location 来暴露状态页:

server {
    listen 127.0.0.1:8080;
    
    location /nginx_status {
        stub_status on;
        allow 127.0.0.1;
        deny all;
    }
}

配置完重载 Nginx:

nginx -s reload

然后访问 http://127.0.0.1:8080/nginx_status 确认能看到类似下面的内容:

Active connections: 2 
server accepts handled requests
 12345 12345 67890 
Reading: 0 Writing: 1 Waiting: 1

有这些输出说明 stub_status 生效了。


安装与启动

Docker 方式

docker run -d -p 9113:9113 fish/nginx-exporter \
  -nginx.scrape_uri=http://172.17.42.1:8080/nginx_status

Docker 里 172.17.42.1 是默认的宿主机网关地址,如果你改了 Docker 网络配置,记得换成实际的宿主 IP。

二进制方式

从 Releases 页面下载对应平台的二进制文件:

wget https://github.com/discordianfish/nginx_exporter/releases/...
tar xvf nginx_exporter_*.tar.gz
./nginx_exporter -nginx.scrape_uri=http://127.0.0.1:8080/nginx_status

默认监听 9113 端口。


配置参数

参数 默认值 说明
-nginx.scrape_uri http://127.0.0.1:8080/nginx_status Nginx 状态页的 URL
-web.listen-address :9113 Exporter 监听地址
-web.telemetry-path /metrics 指标路径

查看所有参数:

./nginx_exporter --help

收集的指标

这个 exporter 采集的指标比较基础,主要来自 Nginx 的 stub_status

指标 含义
nginx_connections_active 当前活跃连接数
nginx_connections_accepted_total 从启动到现在累计接受的连接数
nginx_connections_handled_total 从启动到现在累计成功处理的连接数
nginx_connections_reading 正在读取请求头的连接数
nginx_connections_writing 正在写响应的连接数
nginx_connections_waiting 空闲长连接数
nginx_http_requests_total 从启动到现在累计处理的请求数

常用 PromQL

# Nginx 是否在线
nginx_up

# 当前活跃连接数
nginx_connections_active

# 每秒请求数
rate(nginx_http_requests_total[5m])

# 成功处理率(接近 100% 才正常)
nginx_connections_handled_total / nginx_connections_accepted_total * 100

# 活跃 vs 空闲连接
nginx_connections_active - nginx_connections_waiting

和其他 Nginx Exporter 的对比

方案 优点 缺点
discordianfish/nginx_exporter 极简,只依赖 stub_status 指标少,只有基础连接和请求
nginx-vts-exporter 指标更丰富(每台虚拟主机、每个 upstream) 需要装 VTS 模块
nginxinc/nginx-prometheus-exporter 官方维护,Nginx Plus 有很多高级指标 开源版指标也少

怎么选?

  • 只是简单看看 Nginx 死活和 QPS → 用这个就够了
  • 需要看到每个域名的流量 → 考虑 VTS 方案
  • 用 Nginx Plus → 直接上 nginx-prometheus-exporter
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐