Prometheus Metrics
To monitor PostgreSQL with Prometheus, you can use pg_exporter — a lightweight, modular Prometheus exporter written in Rust designed to expose only the metric domains you need with minimal overhead.
Create a dedicated monitoring user#
Use PostgreSQL's built-in pg_monitor role to grant read-only access to monitoring views without superuser privileges:
CREATE USER postgres_exporter WITH PASSWORD 'strong_password';
GRANT pg_monitor TO postgres_exporter;
When running
pg_exporterlocally on the database host, you can use peer authentication over the Unix socket and omit the password.
Install & Run#
Install via Cargo, or use the pre-built container images (ghcr.io/nbari/pg_exporter) from nbari/pg_exporter:
cargo install pg_exporter
Run using a DSN flag (--dsn), environment variable (PG_EXPORTER_DSN), or secret file (PG_EXPORTER_DSN_FILE):
pg_exporter \
--dsn "postgresql://postgres_exporter@localhost:5432/postgres"
Using a local Unix socket:
pg_exporter \
--dsn "postgresql:///postgres?host=/var/run/postgresql&user=postgres_exporter"
Or with Docker / Podman:
docker run -d \
-e PG_EXPORTER_DSN="postgresql://postgres_exporter:password@db-host:5432/postgres" \
-p 9432:9432 \
ghcr.io/nbari/pg_exporter:latest
By default, pg_exporter listens on port 9432 (override with --port).
Modular collectors#
Enable only the collectors relevant to your workload to keep scrapes fast and avoid unused high-cardinality metrics:
pg_exporter \
--dsn "postgresql://postgres_exporter@localhost:5432/postgres" \
--port 9432 \
--collector.default \
--collector.activity \
--collector.database \
--collector.locks \
--collector.replication \
--collector.vacuum \
--collector.index
Run pg_exporter --help for the full list of collectors and configuration options.
Prometheus scrape configuration#
Add the target to your prometheus.yml:
scrape_configs:
- job_name: postgresql
static_configs:
- targets:
- pg01.example.com:9432Verify metrics#
Confirm the exporter is serving metrics on /metrics:
curl -s http://127.0.0.1:9432/metrics | head -n 20