Notebook Clank's Engineering Notebook
Book / Page No. 1 · P-002
中文
P-002

PostgreSQL observability in practice

A practice project: PostgreSQL metrics via Prometheus, logs via Alloy and Loki, all viewed in Grafana, with each service introduced in setup order.

Period
2026.11
Role
Solo practice
Stack
PostgreSQL · Prometheus · postgres_exporter · Grafana Alloy · Loki · Grafana · Docker Compose
In this entry

The problem

I wanted to see how PostgreSQL is doing in one place. When metrics (connection counts, query volume, and so on) and logs live in different places, it’s hard to line them up when something goes wrong. This is a self-practice project with the goal of bringing both into Grafana.

Architecture

Data takes two routes, and both end up in Grafana:

Architecture: postgres_exporter exposes the metrics and Prometheus scrapes them; Alloy reads the logs through the Docker API and pushes them to Loki; Grafana queries both with PromQL and LogQL

Type Route
Metrics PostgreSQL → postgres_exporter → Prometheus → Grafana
Logs PostgreSQL container output → Docker Engine → Alloy → Loki → Grafana

The two routes work in opposite directions: Prometheus pulls the metrics, while Alloy pushes the logs to Loki.

Setup steps

The monitoring services share one Docker Compose file (config file paths changed to relative paths). The services below are introduced in dependency order: Loki first, because Alloy, Prometheus, and Grafana all have depends_on: loki, and Grafana last, because it queries everything before it.

Volumes and networks shared by the whole Compose file:

volumes:
  loki_data:
  grafana_data:
  prometheus_data:

networks:
  monitoring:
  postgres_postgresnetwork:
    external: true
  • monitoring: the network the monitoring services use to talk to each other. On the same network, services can reach each other by name (for example http://loki:3100).
  • postgres_postgresnetwork: the network created by the PostgreSQL Compose project, marked external here so it can be reused.

0. Prerequisite: PostgreSQL and postgres_exporter

PostgreSQL and postgres_exporter live in a separate Compose project on the postgres_postgresnetwork network. postgres_exporter connects to PostgreSQL, queries its statistics, and exposes them in a format Prometheus understands. That Compose file is outside the scope of this page.

1. Loki: storing logs

loki:
  image: grafana/loki:latest
  ports:
    - "3100:3100"
  command: -config.file=/etc/loki/local-config.yaml
  volumes:
    - loki_data:/loki
    - ./loki/loki-config.yaml:/etc/loki/local-config.yaml:ro
  networks: [monitoring]

Loki stores and queries logs. It doesn’t collect logs by itself; it waits for them to be pushed, in this case by Alloy. Log data lives in the loki_data volume, so it survives container rebuilds.

loki-config.yaml

auth_enabled: false

server:
  http_listen_port: 3100

common:
  instance_addr: 127.0.0.1
  path_prefix: /loki
  storage:
    filesystem:
      chunks_directory: /loki/chunks
      rules_directory: /loki/rules
  replication_factor: 1
  ring:
    kvstore:
      store: inmemory

schema_config:
  configs:
    - from: 2020-10-24
      store: tsdb
      object_store: filesystem
      schema: v13
      index:
        prefix: index_
        period: 24h

limits_config:
  retention_period: 72h

compactor:
  working_directory: /loki/compactor
  retention_enabled: true
  delete_request_store: filesystem

ruler:
  alertmanager_url: http://localhost:9093
Setting Meaning
auth_enabled: false Turns off multi-tenancy: all logs belong to a single tenant, so pushes and queries don’t need a tenant ID
common Single-node mode: data is stored on the local filesystem under /loki, with one replica (replication_factor: 1) and the ring state kept in memory (inmemory)
schema_config The index uses the tsdb store with the v13 schema, with a new index every 24 hours
retention_period: 72h Logs are kept for 3 days
compactor Old logs are only deleted according to the retention period when retention_enabled: true is set; retention_period alone has no effect
ruler Where alerting rules send alerts. There’s no Alertmanager in this environment, so it currently does nothing

Logs are kept for 3 days, shorter than the 7 days of Prometheus metrics. For anything older than 3 days, Grafana shows metrics but no logs.

The config file ends with a comment: by default Loki sends anonymous usage statistics to Grafana Labs. To turn this off, add analytics: reporting_enabled: false.

Check that Loki is up:

curl http://localhost:3100/ready

A response of ready means Loki can accept logs. Right after startup it may report that it isn’t ready yet; wait a few seconds and try again.

2. Alloy: collecting container logs

alloy:
  image: grafana/alloy:latest
  ports:
    - "12345:12345"
  volumes:
    - ./alloy/config.alloy:/etc/alloy/config.alloy:ro
    - /var/lib/docker/containers:/var/lib/docker/containers:ro
    - /var/run/docker.sock:/var/run/docker.sock:ro
  command:
    - run
    - /etc/alloy/config.alloy
    - --server.http.listen-addr=0.0.0.0:12345
  depends_on: [loki]
  networks: [monitoring]

Through the mounted docker.sock, Alloy calls the Docker API to find running containers and read their logs, then pushes the logs to Loki.

An Alloy configuration is a pipeline of components. Alloy’s admin UI (port 12345) shows the actual pipeline:

Alloy pipeline: four components chained in order: discovery.docker, discovery.relabel, loki.source.docker, loki.write

Component Job
discovery.docker "containers" Finds running containers through the Docker API and produces a list of targets
discovery.relabel "containers" Copies the container name and image name into container and image labels
loki.source.docker "containers" Reads each target container’s logs through the Docker API
loki.write "default" Pushes the logs to Loki

On the admin UI’s Components page, all four components show as Healthy, which means the pipeline is working.

config.alloy

discovery.docker "containers" {
  host = "unix:///var/run/docker.sock"
}

discovery.relabel "containers" {
  targets = discovery.docker.containers.targets

  rule {
    source_labels = ["__meta_docker_container_name"]
    target_label  = "container"
  }

  rule {
    source_labels = ["__meta_docker_container_image"]
    target_label  = "image"
  }
}

loki.source.docker "containers" {
  host       = "unix:///var/run/docker.sock"
  targets    = discovery.relabel.containers.output
  forward_to = [loki.write.default.receiver]
}

loki.write "default" {
  endpoint {
    url = "http://loki:3100/loki/api/v1/push"
  }
}
  • Components reference each other as “component type.name.export”, for example discovery.relabel.containers.output. This is also how the admin UI draws the pipeline.
  • The targets from discovery.docker carry temporary labels starting with __meta_, which are dropped at the end. That’s why discovery.relabel copies the needed information (container name, image) into real labels, so they can be used to filter in Loki later.
  • This config collects logs from every container on the host, not just PostgreSQL. Filter by the container label when querying.

Notes

  • Container names start with /: Docker reports container names like /postgres, and this config keeps them as they are, so the container label value includes the / as well. Queries need to use {container="/postgres"}. To strip it, add regex = "/(.*)" to the rule.
  • The /var/lib/docker/containers mount isn’t used right now: loki.source.docker reads logs through the Docker API, not from the files in that folder. You only need it if you switch to a file-based component such as loki.source.file.
  • Admin UI security: --server.http.listen-addr=0.0.0.0:12345 lets anyone who can reach the host open the admin UI, over unencrypted HTTP. If the host isn’t limited to a private network or VPN, restrict who can connect or don’t expose this port.

Check that Alloy is sending logs to Loki: once all four components show as Healthy in the admin UI, ask Loki which labels it has:

curl http://localhost:3100/loki/api/v1/labels

If the result includes container and image, Alloy is pushing logs and the relabel rules are working.

3. Prometheus: collecting metrics

prometheus:
  image: prom/prometheus:latest
  ports:
    - "9090:9090"
  volumes:
    - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
    - prometheus_data:/prometheus
  command:
    - --config.file=/etc/prometheus/prometheus.yml
    - --storage.tsdb.retention.time=7d
  networks: [postgres_postgresnetwork, monitoring]
  • Prometheus joins two networks: postgres_postgresnetwork to reach postgres_exporter and scrape metrics, and monitoring so Grafana can query it. It’s the only monitoring service connected to the PostgreSQL network.
  • Data is kept for only 7 days (--storage.tsdb.retention.time=7d); a practice environment doesn’t need more.

prometheus.yml

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets:
          - prometheus:9090
  - job_name: postgresql
    static_configs:
      - targets:
          - postgres-exporter:9187
  • Metrics are scraped every 15 seconds (scrape_interval: 15s).
  • The prometheus job scrapes Prometheus’s own metrics, which shows whether Prometheus itself is healthy.
  • The postgresql job scrapes postgres_exporter. postgres-exporter is its service name in the PostgreSQL Compose project; containers on the same Docker network can reach each other by service name. 9187 is postgres_exporter’s default port.
  • In Grafana queries, filter PostgreSQL metrics with job="postgresql".

Check that Prometheus is scraping:

  1. Open http://localhost:9090/targets. Both the prometheus and postgresql jobs should be UP. If postgresql is DOWN, Prometheus usually isn’t on postgres_postgresnetwork, or the service name or port is wrong.
  2. Run pg_up on Prometheus’s query page. A result of 1 means the exporter is running and can also reach PostgreSQL. If up{job="postgresql"} is 1 but pg_up is 0, the problem is the exporter’s PostgreSQL credentials or connection settings.

4. Grafana: data sources and dashboard

grafana:
  image: grafana/grafana:latest
  ports:
    - "3200:3000"
  volumes:
    - grafana_data:/var/lib/grafana
  depends_on: [loki, prometheus]
  networks: [monitoring]

Grafana is exposed on port 3200, mapped to 3000 inside the container. After it starts, add two data sources. Since everything is on the monitoring network, they connect by service name:

Data source URL
Prometheus http://prometheus:9090
Loki http://loki:3100

Then build a dashboard that puts metrics and logs on one page:

The postgresql dashboard in Grafana: metric panels for status, connections, disk usage, and transaction rates on top, and a PostgreSQL log panel at the bottom (log contents pixelated; the UI is in Chinese)

Panel Shows
Up Whether PostgreSQL is reachable (1 means up)
Connections Current total number of connections
Disk usage Space used by each database
5-minute average transactions Average transaction rate per database over 5 minutes
Total transactions per second Transactions per second across all databases
Cache hit ratio Share of data reads served from cache
Connections per database Number of connections for each database
log PostgreSQL logs queried from Loki, such as connection and authentication records

The first seven panels get their data from Prometheus and the log panel from Loki, so when something goes wrong you can compare metrics and logs on the same screen.

Check that Grafana is connected:

  1. After adding each data source, click Save & test. Both should report success.
  2. In Explore, query pg_up against Prometheus and {container="/postgres"} against Loki. If both return data, you’re ready to build the dashboard.

Queries (reference)

The queries below are common patterns based on the standard postgres_exporter metrics, provided for reference. They are not the exact queries this dashboard uses. Metric and label names may differ depending on the exporter version and configuration.

The first seven panels query Prometheus with PromQL:

# Up: 1 when the exporter can reach PostgreSQL
pg_up

# Connections: connections in pg_stat_activity, counted per database and state (active, idle, etc.), then summed
sum(pg_stat_activity_count)

# Disk usage: size of each database (bytes)
pg_database_size_bytes

# 5-minute average transactions: commits + rollbacks per second for each database, averaged over 5 minutes
rate(pg_stat_database_xact_commit[5m]) + rate(pg_stat_database_xact_rollback[5m])

# Total transactions per second: summed across all databases
sum(rate(pg_stat_database_xact_commit[5m]) + rate(pg_stat_database_xact_rollback[5m]))

# Cache hit ratio: blocks read from cache ÷ all blocks read (set the panel unit to percent)
sum(rate(pg_stat_database_blks_hit[5m]))
  / (sum(rate(pg_stat_database_blks_hit[5m])) + sum(rate(pg_stat_database_blks_read[5m])))

# Connections per database
pg_stat_database_numbackends

A few things to note:

  • Metrics like xact_commit and blks_hit are counters that only go up, so their raw values aren’t meaningful. Use rate() to turn them into a per-second rate of change.
  • rate() is computed for each database first, then added up with sum(). Doing it the other way round (sum first, then rate) gives wrong results when a counter resets.
  • Disk usage and connection counts are current values (gauges) and don’t need rate().

Other common metric queries you can add as new panels:

# Connection usage: current connections as a share of max_connections; near 1, new connections get refused
sum(pg_stat_activity_count) / max(pg_settings_max_connections)

# Connections grouped by state (active, idle, idle in transaction, etc.)
sum by (state) (pg_stat_activity_count)

# Longest transaction duration (seconds): long-running transactions block VACUUM and hold locks
max(pg_stat_activity_max_tx_duration)

# Deadlocks per second
sum(rate(pg_stat_database_deadlocks[5m]))

# Rollback ratio: rollbacks as a share of all transactions; a sudden rise usually means the application is failing
sum(rate(pg_stat_database_xact_rollback[5m]))
  / sum(rate(pg_stat_database_xact_commit[5m]) + rate(pg_stat_database_xact_rollback[5m]))

# Row operations per second, split by operation type
sum(rate(pg_stat_database_tup_inserted[5m]))
sum(rate(pg_stat_database_tup_updated[5m]))
sum(rate(pg_stat_database_tup_deleted[5m]))

# Bytes written to temporary files per second: used when sorts or hashes exceed work_mem
sum(rate(pg_stat_database_temp_bytes[5m]))

# Current number of locks, grouped by lock mode
sum by (mode) (pg_locks_count)

# The 3 largest databases
topk(3, pg_database_size_bytes)

# How long PostgreSQL has been running (seconds); resets to zero on restart
time() - pg_postmaster_start_time_seconds

# Dead tuples per table; a number that keeps growing means VACUUM can't keep up
topk(10, pg_stat_user_tables_n_dead_tup)

The last query needs the exporter’s stat_user_tables collector, which isn’t enabled in some versions or configurations. If it returns no data, check that first.

The log panel queries Loki with LogQL:

{container="/postgres"}

The container label comes from Alloy’s discovery.relabel, and its value keeps the leading / (see the Alloy notes); this assumes the PostgreSQL container is called postgres. To see only connection-related records, add a filter:

{container="/postgres"} |= "connection"

Other common log queries:

# Only logs at ERROR level or above
{container="/postgres"} |~ "ERROR|FATAL|PANIC"

# Number of errors per 5 minutes, for a trend graph or an alert
sum(count_over_time({container="/postgres"} |~ "ERROR|FATAL|PANIC" [5m]))

# Failed password authentication, useful for spotting password guessing
{container="/postgres"} |= "password authentication failed"

# Hide the flood of connection records from health checks (such as pg_isready)
{container="/postgres"} != "pg_isready"

# Log lines per second for each container, to find the noisiest one
sum by (container) (rate({container=~".+"}[5m]))

# Filter by image, for example every container running a postgres image
{image=~"postgres.*"}
  • |= means contains, != means does not contain, and |~ matches a regular expression.
  • Functions like count_over_time and rate turn logs into numbers that can be graphed like metrics.
  • The image label also comes from Alloy’s discovery.relabel.
  • To find slow queries from the logs, first set log_min_duration_statement in PostgreSQL so that long-running SQL is logged, then filter with |= "duration:".

Security notes

This is a practice environment, so many settings favor convenience. If the host isn’t limited to a private network, pay attention to the following:

  • Don’t expose ports you don’t need: Loki (3100), Prometheus (9090), and Alloy (12345) have no authentication, so anyone who can reach the host can query the logs and metrics. Grafana already reaches Loki and Prometheus over the monitoring network, so these ports don’t need to be public. Remove the ports entries or bind them to localhost, for example "127.0.0.1:9090:9090".
  • A read-only docker.sock mount doesn’t mean read-only access: :ro only stops the socket file itself from being modified. Through it, the Docker API can still create and stop containers. Control of the Alloy container is close to control of Docker on the whole host, so keep the Alloy image source and admin UI locked down.
  • Change Grafana’s default password: the default login is admin / admin; change it on first login.
  • Give the exporter its own account: for postgres_exporter, create a PostgreSQL account that only has the pg_monitor role instead of using a superuser. pg_monitor is PostgreSQL’s built-in monitoring role; it can read statistics but can’t change data.

What I did

I set up the whole environment myself, from deploying the services and configuring the networks to wiring up the data sources.

Key takeaways

  • Two routes: Prometheus pulls the metrics on a schedule, Alloy pushes the logs to Loki, and Grafana queries both.
  • Setup order: Loki → Alloy → Prometheus → Grafana. Confirm each step works before moving on, so errors are easier to trace.
  • Alloy reads logs through the Docker API, not from log files, so docker.sock is what it actually needs.
  • The leading / in container names: unless you strip it, LogQL has to use {container="/postgres"} or it returns nothing.
  • Counters need rate() before sum(): the raw value of an ever-increasing metric like xact_commit isn’t meaningful.
  • Loki retention only works with the compactor enabled, and here logs are kept for 3 days while metrics are kept for 7.
  • Network layout: only Prometheus joins both the PostgreSQL network and the monitoring network; no other service needs to touch the database.