Home Server › Containers

Running shared MariaDB and Redis containers in a homelab

Build a shared MariaDB and Redis stack with Docker Compose using utf8mb4, AOF/RDB persistence, isolated bridge networks, Adminer, and automated backups.

Running shared MariaDB and Redis containers in a homelab

Running a separate database container for every homelab app burns through RAM fast and fragments your backup scripts. This guide sets up a shared MariaDB and Redis stack with Docker Compose, covering utf8mb4 encoding, AOF/RDB hybrid persistence, isolated bridge networking, Adminer behind Nginx Proxy Manager, and automated dumps.


Why consolidate into a shared database and cache tier

When you self-host n8n, Vaultwarden, Wiki.js, Uptime Kuma, and personal Spring Boot or Node.js projects on a Mac mini or mini PC, it’s tempting to drop a dedicated database container into each service’s docker-compose.yml.

That pattern quickly runs into three practical limits:

  1. Wasted RAM and CPU: Most homelab nodes have 16–32 GB of RAM. Every standalone database allocates its own InnoDB buffer pool, connection buffers, and cache memory, burning gigabytes even while idle.
  2. Fragmented backups and upgrades: Separate data volumes across a dozen directories mean separate backup scripts, inconsistent retention policies, and tedious version upgrades.
  3. Host port collisions: Mapping 3306, 3307, 3308, and so on makes it harder to track which port belongs to which app.

Consolidating into one shared MariaDB instance and one shared Redis instance solves all three. Inside MariaDB, each application gets its own logical database (n8n_db, wiki_db, dev_app_db) and a least-privilege user (n8n_user, wiki_user, dev_user). Inside Redis, services share memory safely via key prefixes or separate database indexes.

When shouldn’t you share a single instance? If one workload needs a different major database version, requires heavy write isolation where noisy neighbors can stall other apps, or demands strict compliance boundaries, give that service its own dedicated container. For typical homelab stacks (or if you later migrate to a PostgreSQL and Redis v2 stack), a single shared tier is far easier to operate.


Network isolation and traffic flow

Because this tier holds data for every service in your homelab, never expose ports 3306 or 6379 to the public internet. Instead, place MariaDB and Redis on an internal Docker bridge network (homelab-db-net) so only containers explicitly attached to that network can reach them.

flowchart TD
    subgraph External["External Internet and Admin"]
        AdminBrowser["Admin Browser<br/>(https://db.namju.kim)"]
    end

    subgraph ReverseProxy["Nginx Proxy Manager Ingress"]
        NPM["NPM Reverse Proxy<br/>(TLS termination / LAN IP allowlist)"]
    end

    subgraph ServiceLayer["Homelab Application Containers"]
        SVC_n8n["n8n Workflow Container"]
        SVC_Wiki["Wiki.js Container"]
        SVC_Dev["Spring Boot Backend Container"]
    end

    subgraph DatabaseTier["Shared Database Tier (homelab-db-net)"]
        Adminer["Adminer Web DB UI (Port 8080)"]
        MDB_Engine["MariaDB Server (Port 3306)"]
        DB1[("db_n8n")]
        DB2[("db_wiki")]
        DB3[("db_dev")]
    end

    subgraph CacheTier["Shared Cache Tier"]
        RDS_Engine["Redis Server (Port 6379)"]
        RDS_Mem[("In-Memory Cache / Sessions / Queues")]
    end

    subgraph Storage["Persistent Volumes"]
        Vol_MDB[("MariaDB Data Volume<br/>(/var/lib/mysql)")]
        Vol_RDS[("Redis AOF/RDB Volume<br/>(/data)")]
    end

    AdminBrowser -->|"HTTPS 443"| NPM
    NPM -->|"Internal proxy"| Adminer
    Adminer -->|"MySQL protocol"| MDB_Engine

    SVC_n8n -->|"mariadb:3306"| MDB_Engine
    SVC_Wiki -->|"mariadb:3306"| MDB_Engine
    SVC_Dev -->|"mariadb:3306"| MDB_Engine
    SVC_Dev -->|"redis:6379"| RDS_Engine

    MDB_Engine --> DB1
    MDB_Engine --> DB2
    MDB_Engine --> DB3
    RDS_Engine --> RDS_Mem

    MDB_Engine --> Vol_MDB
    RDS_Engine --> Vol_RDS

The network layout follows three rules:

  • Internal DNS communication: App containers join homelab-db-net and connect directly to mariadb:3306 and redis:6379 with zero host port forwarding.
  • Isolated web UI (Adminer): Adminer sits on both homelab-db-net and npm-network, letting you manage schemas over HTTPS (db.namju.kim) without exposing the database engine itself to the proxy network.
  • Loopback-only host ports: Bind 3306 and 6379 strictly to 127.0.0.1 so you can still inspect data from the host (or over an SSH tunnel) without opening 0.0.0.0.

Configuring MariaDB with utf8mb4 and init scripts

Legacy utf8 (3-byte) encodings in MySQL and MariaDB reject 4-byte Unicode characters such as emojis (😀, 🎉) and extended CJK characters with Incorrect string value errors. Enforce utf8mb4 and utf8mb4_unicode_ci globally across both client and server sections.

Custom my.cnf

Here’s a tuned configuration sized for a homelab node allocating 1 GB to the InnoDB buffer pool:

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
# ~/homelab/database/config/mariadb/my.cnf

[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

[mysqld]
# Global character set and collation (full 4-byte Unicode & emoji support)
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
character_set_server = utf8mb4
collation_server = utf8mb4_unicode_ci

# Connection pool and timeouts
max_connections = 150
max_connect_errors = 1000
connect_timeout = 10
wait_timeout = 600
interactive_timeout = 600

# InnoDB buffer pool and I/O tuning (1 GB target for homelab RAM)
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_log_buffer_size = 16M
innodb_file_per_table = 1
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT

# Slow query log (flag queries taking over 2 seconds)
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mariadb-slow.log
long_query_time = 2

# Enforce lowercase table names for cross-OS compatibility
lower_case_table_names = 1

Setting innodb_flush_log_at_trx_commit = 2 flushes the redo log to disk once per second instead of on every commit. That cuts SSD write wear and speeds up writes noticeably while limiting potential loss on a sudden power outage to roughly one second of transactions—a solid trade-off for a homelab.

Initialization SQL (initdb.d/01-init-databases.sql)

MariaDB automatically runs any .sql files mounted into /docker-entrypoint-initdb.d on first boot (when the data directory is empty). Pre-create each app’s database and scoped user here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- ~/homelab/database/initdb.d/01-init-databases.sql

-- 1. n8n workflow database and user
CREATE DATABASE IF NOT EXISTS `n8n_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'n8n_user'@'%' IDENTIFIED BY 'n8n_strong_secret_password!';
GRANT ALL PRIVILEGES ON `n8n_db`.* TO 'n8n_user'@'%';

-- 2. Wiki.js database and user
CREATE DATABASE IF NOT EXISTS `wiki_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'wiki_user'@'%' IDENTIFIED BY 'wiki_strong_secret_password!';
GRANT ALL PRIVILEGES ON `wiki_db`.* TO 'wiki_user'@'%';

-- 3. Development project database and user
CREATE DATABASE IF NOT EXISTS `dev_app_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'dev_user'@'%' IDENTIFIED BY 'dev_strong_secret_password!';
GRANT ALL PRIVILEGES ON `dev_app_db`.* TO 'dev_user'@'%';

-- Apply privileges immediately
FLUSH PRIVILEGES;

Configuring Redis authentication and hybrid persistence

By default, Redis keeps everything in RAM, so an unexpected reboot wipes sessions and cached state. Unauthenticated Redis instances exposed on a network are also frequent targets for cryptominer exploits.

Enable password authentication and AOF/RDB hybrid persistence in a custom redis.conf:

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
# ~/homelab/database/config/redis/redis.conf

# 1. Network and security
bind 0.0.0.0
protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300

# Required: strong authentication password
requirepass your_strong_redis_auth_password!

# 2. RDB binary snapshot intervals
# Snapshot after 900s (15m) if at least 1 key changed
save 900 1
# Snapshot after 300s (5m) if at least 10 keys changed
save 300 10
# Snapshot after 60s (1m) if at least 10,000 keys changed
save 60 10000

stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /data

# 3. AOF (Append Only File) command log
appendonly yes
appendfilename "appendonly.aof"
# Sync to disk every second (best balance of durability and latency)
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

# 4. Memory cap and eviction policy (512 MB limit for homelab)
maxmemory 512mb
maxmemory-policy allkeys-lru
  • RDB saves compact point-in-time binary snapshots (dump.rdb), keeping container restarts fast.
  • AOF appends every write command to appendonly.aof and syncs once per second (everysec), capping data loss during a crash to at most one second.
  • Hybrid mode (default since Redis 5.0) combines an RDB preamble with trailing AOF records, giving you both fast recovery and minimal data loss.

Putting the stack together with Docker Compose

Organize configs, init scripts, and persistent volumes under ~/homelab/database/:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
~/homelab/database/
├── docker-compose.yml
├── .env.example
├── .env
├── config/
│   ├── mariadb/
│   │   └── my.cnf
│   └── redis/
│       └── redis.conf
├── initdb.d/
│   └── 01-init-databases.sql
└── data/
    ├── mariadb/         # MariaDB tablespace files
    └── redis/           # dump.rdb and appendonly.aof

Environment variables (.env.example)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ~/homelab/database/.env.example

# MariaDB root password
MARIADB_ROOT_PASSWORD=super_secret_mariadb_root_password!

# MariaDB host bind address (loopback only)
MARIADB_HOST_PORT=127.0.0.1:3306

# Redis authentication password
REDIS_PASSWORD=super_secret_redis_auth_password!

# Redis host bind address (loopback only)
REDIS_HOST_PORT=127.0.0.1:6379

# Timezone
TZ=Asia/Seoul

Complete docker-compose.yml

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
67
68
69
70
71
72
73
74
75
# ~/homelab/database/docker-compose.yml
services:
  mariadb:
    image: mariadb:11.4
    container_name: mariadb
    restart: unless-stopped
    environment:
      MARIADB_ROOT_PASSWORD: ${MARIADB_ROOT_PASSWORD}
      TZ: ${TZ:-Asia/Seoul}
    volumes:
      - ./data/mariadb:/var/lib/mysql
      - ./config/mariadb/my.cnf:/etc/mysql/conf.d/custom.cnf:ro
      - ./initdb.d:/docker-entrypoint-initdb.d:ro
    ports:
      # Localhost only for debugging; blocks external interface exposure
      - "${MARIADB_HOST_PORT:-127.0.0.1:3306}:3306"
    networks:
      - homelab-db-net
    healthcheck:
      test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
      interval: 15s
      timeout: 5s
      retries: 5
      start_period: 30s
    deploy:
      resources:
        limits:
          memory: 2048M

  redis:
    image: redis:7.4-alpine
    container_name: redis
    restart: unless-stopped
    command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
    environment:
      TZ: ${TZ:-Asia/Seoul}
    volumes:
      - ./data/redis:/data
      - ./config/redis/redis.conf:/usr/local/etc/redis/redis.conf:ro
    ports:
      - "${REDIS_HOST_PORT:-127.0.0.1:6379}:6379"
    networks:
      - homelab-db-net
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 10s
    deploy:
      resources:
        limits:
          memory: 768M

  adminer:
    image: adminer:4-fastcgi-apache
    container_name: adminer
    restart: unless-stopped
    depends_on:
      mariadb:
        condition: service_healthy
    networks:
      - homelab-db-net
      - npm-network
    deploy:
      resources:
        limits:
          memory: 256M

networks:
  homelab-db-net:
    name: homelab-db-net
    driver: bridge
  npm-network:
    external: true

Create the data directories and start the stack:

1
2
mkdir -p data/mariadb data/redis
docker compose up -d

Exposing Adminer and connecting client containers

Adminer reverse proxy and Access Lists (db.namju.kim)

Add a Proxy Host for db.namju.kim in Nginx Proxy Manager:

  1. Details:
    • Domain Names: db.namju.kim
    • Forward Host: adminer (attached to both npm-network and homelab-db-net)
    • Forward Port: 80 (default port for adminer:4-fastcgi-apache)
    • Block Common Exploits: ON
  2. SSL:
    • Select your *.namju.kim wildcard certificate and enable Force SSL.
  3. Access Lists (required): Never leave a database web UI open to the public internet. Create an NPM Access List and attach it to this host:
    • Name: Homelab-Internal-Only
    • Authorization: Add an HTTP Basic Auth credential as a second gate.
    • Access rules: Allow private RFC 1918 ranges (192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12) and deny everything else.

Connecting other containers

Any application stack living in a separate directory can reach MariaDB or Redis by declaring homelab-db-net as an external network:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Example: ~/homelab/n8n/docker-compose.yml
services:
  n8n:
    image: docker.n8n.io/n8nio/n8n:latest
    restart: unless-stopped
    environment:
      - DB_TYPE=mariadb
      - DB_MYSQLDB_DATABASE=n8n_db
      - DB_MYSQLDB_HOST=mariadb        # Resolved via Docker embedded DNS
      - DB_MYSQLDB_PORT=3306
      - DB_MYSQLDB_USER=n8n_user
      - DB_MYSQLDB_PASSWORD=n8n_strong_secret_password!
    networks:
      - homelab-db-net
      - npm-network

networks:
  homelab-db-net:
    external: true
  npm-network:
    external: true

Docker’s embedded DNS (127.0.0.11) resolves mariadb:3306 and redis:6379 automatically without exposing any database ports on the host.


Automated backups, recovery, and takeaways

With every service’s schema consolidated into one MariaDB instance, a single cron script handles backups for the whole homelab.

Daily MariaDB dump script

Run mariadb-dump inside the container with --single-transaction for consistent InnoDB snapshots without locking tables:

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
#!/usr/bin/env bash
# ~/homelab/database/scripts/backup-databases.sh
set -euo pipefail

BACKUP_DIR="/home/user/homelab/backups/mariadb"
DATE_STR="$(date +%Y%m%d_%H%M%S)"
ENV_FILE="/home/user/homelab/database/.env"

# Load credentials from .env
if [ -f "${ENV_FILE}" ]; then
  # shellcheck source=/dev/null
  export $(grep -v '^#' "${ENV_FILE}" | xargs)
fi

mkdir -p "${BACKUP_DIR}"

echo "[${DATE_STR}] Starting automated MariaDB database backup..."

# Databases to dump
DATABASES=("n8n_db" "wiki_db" "dev_app_db")

for DB in "${DATABASES[@]}"; do
  FILE_NAME="${BACKUP_DIR}/${DB}_${DATE_STR}.sql.gz"
  echo "Dumping database: ${DB} -> ${FILE_NAME}"
  
  docker exec -i mariadb mariadb-dump \
    -u root \
    -p"${MARIADB_ROOT_PASSWORD}" \
    --single-transaction \
    --quick \
    --routines \
    --triggers \
    "${DB}" | gzip -9 > "${FILE_NAME}"
done

# Prune backups older than 7 days
find "${BACKUP_DIR}" -type f -name "*.sql.gz" -mtime +7 -delete

echo "[${DATE_STR}] MariaDB backup successfully completed."

Redis RDB snapshot backup

Trigger a background save and copy dump.rdb to your backup directory:

1
2
3
4
# Trigger background snapshot and archive dump.rdb
docker exec -i redis redis-cli -a "${REDIS_PASSWORD}" bgsave
sleep 5
cp ~/homelab/database/data/redis/dump.rdb "/home/user/homelab/backups/redis/dump_${DATE_STR}.rdb"

Restoring from a compressed dump

To recover a single database during a migration or incident, stream the compressed dump straight back into mariadb:

1
2
3
# Restore a specific database from a gzipped SQL dump
gunzip < /home/user/homelab/backups/mariadb/n8n_db_20261020_040000.sql.gz | \
  docker exec -i mariadb mariadb -u root -p"${MARIADB_ROOT_PASSWORD}" n8n_db

Summary checklist

  • Consolidate by default: Share one MariaDB and one Redis container across homelab apps to save gigabytes of RAM, isolating each app with its own logical database and user.
  • Lock down the network: Keep database ports bound to 127.0.0.1 and route inter-container traffic over a dedicated bridge network (homelab-db-net).
  • Set utf8mb4 and hybrid persistence early: Avoid broken emoji inserts in MariaDB and wiped sessions in Redis before apps start writing real data.
  • Protect Adminer: Put db.namju.kim behind NPM Access Lists with LAN IP allowlists and HTTP Basic Auth.
  • Automate and test restores: Schedule mariadb-dump + Redis bgsave, prune old archives, and pair the stack with Prometheus and Node Exporter or mysqld and Redis exporters to watch memory and query latency.
This post is licensed under CC BY 4.0 by the author.