Home Server › Containers

Database monitoring with mysqld_exporter and redis_exporter

Collect MariaDB and Redis runtime metrics in Prometheus using mysqld_exporter and redis_exporter in Docker with least-privilege accounts and PromQL queries.

Database monitoring with mysqld_exporter and redis_exporter

Host CPU and memory graphs don’t tell you when MariaDB hits max_connections or when your Redis cache hit ratio collapses. This post shows how to create a least-privilege MariaDB monitoring account, deploy mysqld_exporter and redis_exporter on an isolated Docker network, and query the core database metrics in Prometheus.

Tested with Prometheus v2.54.1, mysqld_exporter v0.15.1, redis_exporter v1.63.0-alpine, MariaDB 11.x, and Redis 7.x.

Why host metrics miss database bottlenecks

After setting up Node Exporter and Prometheus to track host CPU, RAM, and disk usage, I still had a blind spot inside the database layer.

When a Spring Boot service starts throwing HikariCP connection timeouts because MariaDB reached max_connections, or when Redis evicts hot keys and dumps traffic straight onto the database, host CPU can look completely normal right up until requests start failing.

To expose engine internals to Prometheus, I run mysqld_exporter alongside MariaDB and redis_exporter alongside Redis (building on my shared homelab MariaDB and Redis stack):

flowchart TD
    subgraph DataTier["Database Network (database-net)"]
        MDB[("MariaDB 11.x (:3306)")]
        RDS[("Redis 7.x (:6379)")]
    end

    subgraph ExporterTier["Metrics Exporters"]
        ME["mysqld-exporter (:9104/metrics)"]
        RE["redis-exporter (:9121/metrics)"]
    end

    subgraph Observability["Monitoring Engine"]
        PROM["Prometheus (:9090)"]
    end

    ME -->|"SHOW GLOBAL STATUS"| MDB
    RE -->|"INFO ALL"| RDS
    PROM -->|"Scrape every 15s"| ME
    PROM -->|"Scrape every 15s"| RE

Each exporter translates internal status commands (SHOW GLOBAL STATUS for MariaDB, INFO ALL for Redis) into Prometheus text format on /metrics.

When should you skip dedicated exporters? If you only run a single low-traffic dev database that gets reset weekly, docker stats and slow query logs are usually enough. Dedicated exporters become worth the extra containers once multiple services share the same database instance and you need historical connection, query, and cache trends.

Creating a least-privilege MariaDB monitoring user

Passing the MariaDB root password to an exporter container is a bad shortcut. If the exporter is ever misconfigured or compromised, an attacker inherits full read/write access to every schema on the server.

Instead, create a dedicated exporter user with only the privileges needed to read runtime statistics. Connect to MariaDB (mariadb -u root -p) and run:

1
2
3
4
5
6
7
8
-- 1. Create a dedicated monitoring account capped at 3 concurrent connections
CREATE USER 'exporter'@'%' IDENTIFIED BY '${MARIADB_EXPORTER_PASSWORD}' WITH MAX_USER_CONNECTIONS 3;

-- 2. Grant read-only monitoring privileges
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'%';

-- 3. Reload privilege tables
FLUSH PRIVILEGES;

Here is why each grant matters:

  • PROCESS: Lets the exporter read active threads and query states (SHOW PROCESSLIST) to spot slow queries and lock waits.
  • REPLICATION CLIENT: Allows checking replication status (SHOW SLAVE STATUS, SHOW MASTER STATUS) and replication lag.
  • SELECT ON *.*: Required to read table sizes, index stats, and engine metrics from performance_schema and information_schema.
  • WITH MAX_USER_CONNECTIONS 3: Caps the exporter at three connections so a runaway scrape loop can never starve your application’s connection pool.

Generate a random 20+ character password for ${MARIADB_EXPORTER_PASSWORD} instead of reusing an application credential.

Core Redis metrics exposed by redis_exporter

Redis executes commands on a single-threaded event loop, so latency spikes show up quickly when memory saturates or blocking commands pile up. redis_exporter runs INFO ALL under the hood and turns hundreds of fields into Prometheus series.

Four groups of metrics matter most in day-to-day operation:

  1. Memory usage and fragmentation: Compare used_memory_rss against used_memory. When mem_fragmentation_ratio climbs above 1.5, the OS is holding significantly more memory than Redis actually uses.
  2. Client connections: Watch connected_clients for connection leaks and blocked_clients for commands like BLPOP or BRPOP stalling workers.
  3. Throughput: instantaneous_ops_per_sec tracks commands per second so you can correlate traffic surges with backend latency.
  4. Cache hit ratio: Derived from keyspace_hits and keyspace_misses. For a typical read-through cache, I want this staying above 90%.

If your Redis instance enforces requirepass, pass the password to redis_exporter via the REDIS_PASSWORD environment variable.

Docker Compose and network isolation

I extend the existing ~/homelab-monitoring directory so Prometheus and all exporters live in one Compose project:

1
2
3
4
5
~/homelab-monitoring/
├── .env
├── docker-compose.yml
└── prometheus/
    └── prometheus.yml

Environment file (.env)

Keep database credentials in a local .env file and exclude it from Git:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# .env
TZ=Asia/Seoul
PROMETHEUS_PORT=9090

# MariaDB exporter credentials
MARIADB_HOST=mariadb
MARIADB_PORT=3306
MARIADB_EXPORTER_USER=exporter
MARIADB_EXPORTER_PASSWORD=replace_with_strong_mariadb_password

# Redis exporter credentials
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_PASSWORD=replace_with_strong_redis_password

Complete docker-compose.yml

Both exporters attach to two Docker networks: database-net (the existing external network where MariaDB and Redis run) and monitoring-net (where Prometheus scrapes them).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# docker-compose.yml
services:
  # 1. Prometheus server
  prometheus:
    image: prom/prometheus:v2.54.1
    container_name: monitoring-prometheus
    restart: unless-stopped
    user: "65534:65534"
    command:
      - "--config.file=/etc/prometheus/prometheus.yml"
      - "--storage.tsdb.path=/prometheus"
      - "--storage.tsdb.retention.time=30d"
      - "--storage.tsdb.retention.size=20GB"
      - "--storage.tsdb.wal-compression"
      - "--web.enable-lifecycle"
    ports:
      - "${PROMETHEUS_PORT:-9090}:9090"
    volumes:
      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - prometheus_data:/prometheus
    networks:
      - monitoring-net

  # 2. MariaDB Exporter
  mysqld-exporter:
    image: prom/mysqld-exporter:v0.15.1
    container_name: monitoring-mysqld-exporter
    restart: unless-stopped
    environment:
      # DATA_SOURCE_NAME format: user:password@(host:port)/
      DATA_SOURCE_NAME: "${MARIADB_EXPORTER_USER}:${MARIADB_EXPORTER_PASSWORD}@(${MARIADB_HOST}:${MARIADB_PORT})/"
    command:
      - "--collect.global_status"
      - "--collect.global_variables"
      - "--collect.info_schema.innodb_metrics"
      - "--collect.info_schema.processlist"
      - "--collect.info_schema.tables"
      - "--collect.auto_increment.columns"
    networks:
      - monitoring-net
      - database-net

  # 3. Redis Exporter
  redis-exporter:
    image: oliver006/redis_exporter:v1.63.0-alpine
    container_name: monitoring-redis-exporter
    restart: unless-stopped
    environment:
      REDIS_ADDR: "redis://${REDIS_HOST}:${REDIS_PORT}"
      REDIS_PASSWORD: "${REDIS_PASSWORD}"
      REDIS_EXPORTER_LOG_FORMAT: "json"
    networks:
      - monitoring-net
      - database-net

volumes:
  prometheus_data:
    name: homelab_prometheus_data

networks:
  monitoring-net:
    name: homelab_monitoring_net
    driver: bridge
  database-net:
    name: homelab_database_net
    external: true # Existing network shared by MariaDB and Redis

Notice there is no ports: section on mysqld-exporter or redis-exporter. Keeping ports 9104 and 9121 internal to monitoring-net shrinks the host’s attack surface because only Prometheus needs to reach them.

Adding scrape jobs to Prometheus

Update prometheus/prometheus.yml to add scrape jobs for MariaDB and Redis:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# prometheus/prometheus.yml
global:
  scrape_interval: 15s
  evaluation_interval: 15s
  scrape_timeout: 10s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "node-exporter"
    static_configs:
      - targets: ["node-exporter:9100"]

  # MariaDB scrape job
  - job_name: "mariadb"
    scrape_interval: 15s
    scrape_timeout: 10s
    static_configs:
      - targets: ["mysqld-exporter:9104"]
        labels:
          environment: "production"
          service: "mariadb"

  # Redis scrape job
  - job_name: "redis"
    scrape_interval: 15s
    scrape_timeout: 10s
    static_configs:
      - targets: ["redis-exporter:9121"]
        labels:
          environment: "production"
          service: "redis"

Start the new exporter containers with docker compose up -d, then hot-reload Prometheus without dropping any in-flight scrapes:

1
2
# Reload Prometheus config without restarting the container
curl -X POST http://localhost:9090/-/reload

Verifying exporters and diagnostic PromQL queries

Because the exporter ports aren’t published to the host, test them from inside the Prometheus container over monitoring-net:

1
docker exec -it monitoring-prometheus wget -qO- http://mysqld-exporter:9104/metrics | grep mysql_up
1
2
3
# HELP mysql_up Whether the MySQL server is up.
# TYPE mysql_up gauge
mysql_up 1

You can run the same check against http://redis-exporter:9121/metrics | grep redis_up. Seeing mysql_up 1 and redis_up 1 confirms both authentication and network routing work.

Once samples start flowing, these four PromQL queries cover the most common database failure modes:

  1. MariaDB connection saturation (%):
    (mysql_global_status_threads_connected / mysql_global_variables_max_connections) * 100
    

    If this stays above 80%, check for connection leaks in your app or increase the pool budget carefully.

  2. MariaDB queries per second (QPS):
    rate(mysql_global_status_queries[1m])
    

    Shows real-time query volume so you can spot sudden N+1 query regressions after a deployment.

  3. Redis cache hit ratio (%):
    (rate(redis_keyspace_hits_total[5m]) /
    (rate(redis_keyspace_hits_total[5m]) + rate(redis_keyspace_misses_total[5m]))) * 100
    

    Measures how effectively Redis shields your primary database from repeat reads.

  4. Redis memory saturation (%):
    redis_memory_used_bytes / redis_memory_max_bytes * 100
    

    Tracks how close Redis is to its maxmemory limit before key evictions or OOM errors kick in.

Caveats and checklist

A few operational details are easy to overlook when wiring up database exporters:

  • Watch mysqld_exporter collector overhead: Enabling --collect.info_schema.tables is fine on a homelab with dozens of tables, but on servers with thousands of tables it can slow down scrapes. Turn off heavy collectors if scrape duration climbs.
  • Avoid root credentials: Always isolate MariaDB monitoring behind a dedicated user with PROCESS, REPLICATION CLIENT, SELECT, and MAX_USER_CONNECTIONS 3.
  • Keep exporter ports private: Omit host ports: bindings and route scrapes strictly over the internal Docker bridge network.
  • Visualize and alert: Raw PromQL is great for debugging, but for daily visibility and threshold alerts, wire this Prometheus instance into Grafana dashboards and Unified Alerting.
This post is licensed under CC BY 4.0 by the author.