Collecting Nginx metrics with the Prometheus nginx_exporter


Over the past year I’ve rolled out numerous Prometheus exporters to provide visibility into the infrastructure I manage. Exporters are server processes that interface with an application (HAProxy, MySQL, Redis, etc.), and make their operational metrics available through an HTTP endpoint. The nginx_exporter is an exporter for Nginx, and allows you to gather the stub_status metrics in a super easy way.

To use this exporter, you will first need to download the nginx_exporter binary from the projects Github release page. Once downloaded and extracted, you should create a user to run the process as (this isn’t required, but helps to enhance security):

$ useradd -s /bin/false -c 'nginx_exporter service account' -r prometheus

Next, you will need to create a systemd unit file to start and stop the nginx_exporter process:

$ cat /etc/systemd/system/nginx_exporter.service

[Unit]
Description=Prometheus Nginx Exporter
After=network.target

[Service]
ExecStart= /usr/local/bin/nginx-prometheus-exporter -nginx.scrape-uri https://example.com/metrics -web.listen-address=127.0.0.1:9113
Restart=always
User=prometheus
Group=prometheus

[Install]
WantedBy=multi-user.target

$ systemctl enable nginx_exporter && systemctl start nginx_exporter

The example above assumes that you are running the nginx_exporter process on the same server Nginx is running on. To allow the node_exporter to scrape metrics, you will need to add a location stanza similar to the following:

location /metrics {
    stub_status on;
    access_log   off;
    allow 127.0.0.1;
    deny all;
}

That’s it. You can now test the metrics endpoint with your favorite web utility:

$ curl -s localhost:9113/metrics | grep ^nginx

nginx_connections_accepted 77
nginx_connections_active 6
nginx_connections_handled 77
nginx_connections_reading 0
nginx_connections_waiting 5
nginx_connections_writing 1
nginx_http_requests_total 1513
nginx_up 1

If you are using Nginx+ there are a TON more metrics exposed. But for basic website monitoring, these can prove useful.

This article was posted by on 2020-07-07 01:00:00 -0500 -0500