操作场景
Nginx 通过 stub_status 页面暴露了部分监控指标。Nginx Prometheus Exporter 会采集单个 Nginx 实例指标,并将其转化为 Prometheus 可用的监控数据, 最终通过 HTTP 协议暴露给 Prometheus 服务进行采集。我们可以通过 Exporter 上报重点关注的监控指标,用于异常报警和大盘展示。
操作步骤
第一种方式:使用 Docker 容器运行 Exporter
方式1:使用 nginx-prometheus-exporter 通过 Docker 容器快速部署 Exporter。执行 Docker 命令如下:
$ docker run -p 9113:9113 nginx/nginx-prometheus-exporter:0.8.0 -nginx.scrape-uri=http://<nginx>:8080/stub_status
说明:
http://<nginx>:8080/stub_status 需要把<nginx>替换成实际服务的 IP 地址,如 http://192.168.10.10:8080/stub_status
下面都以 192.168.10.10 作为例子,请换成实际服务地址
第二种方式:使用二进制程序运行 Exporter
开启 NGINX stub_status 功能
安装此模块时发生的报错:
报错1:
checking for OS
+ Linux 2.6.32-431.el6.x86_64 x86_64
checking for C compiler ... not found
./configure: error: C compiler cc is not found
解决
执行下面命令解决问题
yum -y install gcc gcc-c++ autoconf automake make
报错2:
./configure: error: the HTTP rewrite module requires the PCRE library. You can either disable the module by using --without-http_rewrite_module option, or install the PCRE library into the system, or build the PCRE library statically from the source with
解决
执行下面命令解决问题
在ubuntu上使用以下命令:sudo apt-get install libpcre3 libpcre3-dev
在centos7上使用以下命令:sudo yum install -y pcre pcre-devel
sudo yum install -y zlib-devel
-
开源 Nginx 提供一个简单页面用于展示状态数据,该页面由 stub_status 模块提供。执行以下命令检查 Nginx 是否已经开启了该模块:
nginx -V 2>&1 | grep -o with-http_stub_status_module
如果在终端中输出 with-http_stub_status_module ,则说明 Nginx 已启用 tub_status 模块。如果未输出任何结果,则可以使用 --with-http_stub_status_module 参数从源码重新配置编译一个 Nginx。示例如下:
./configure --prefix=/usr/local/nginx --with-http_stub_status_module
make & make install
2.确认 stub_status 模块启用之后,修改 Nginx 的配置文件指定 status 页面的 URL。示例如下:
3.检查并重新加载 Nginx的配置使其生效
nginx -t
nginx -s reload
4.完成上述步骤之后,可以通过配置的 URL 查看 Nginx 的指标:
curl http://192.168.10.10:8080/stub_status
Active connections: 45
server accepts handled requests
1056958 1156958 4491319
Reading: 0 Writing: 25 Waiting : 7
运行 NGINX Prometheus Exporter
执行以下命令启动 NGINX Prometheus Exporter:
$ ./nginx-prometheus-exporter -nginx.scrape-uri=http://192.168.10.10:8080/nginx_status
上报指标
nginxexporter_build_info -- exporter 编译信息。
所有的 stub_status 指标。
nginx_up -- 展示上次抓取的状态:1表示抓取成功, 0表示抓取失败。
配置 Prometheus 的抓取 Job
-
Nginx Prometheus Exporter 正常运行后,执行以下命令,将 Job 添加到 Prometheus 的抓取任务中。
...
- job_name: 'nginx_exporter'
static_configs:- targets: ['192.168.10.10:8080']
- job_name: 'nginx_exporter'
-
通常情况下 ,Exporter 和 Nginx 并非共同运行,所以数据上报的 instance 并不能真实描述是哪个实例,为了方便数据的检索和观察,我们可以修改 instance 标签,使用真实的 IP 进行替换以便更加直观。示例如下:
...
- job_name: 'nginx_exporter'
static_configs:- targets: ['192.168.10.10:8080']
relabel_configs: - source_labels: [address]
regex: '.*'
target_label: instance
replacement: '10.0.0.1:80'
- targets: ['192.168.10.10:8080']
查看监控
Prometheus 监控服务在 Grafana 中提供预先配置的 Nginx Exporter Dashboard,您可以根据以下操作步骤查看 Nginx 监控数据。
- 登录 Prometheus 监控服务控制台。
- 单击对应实例 ID 右侧的