Home Server › Containers

Shared PostgreSQL and Redis stack with idempotent DB setup

Consolidate homelab services onto PostgreSQL with SCRAM-SHA-256 and Redis 8, and provision isolated per-service databases with an idempotent Bash script.

Shared PostgreSQL and Redis stack with idempotent DB setup

Managing a separate database container for every self-hosted app wastes memory and multiplies backup chores, while sharing one superuser account breaks isolation. Here is how I built my homelab v2 core data stack with PostgreSQL, Redis 8, and an idempotent Bash provisioning script.

Tested with Docker Compose v2, PostgreSQL 17 (SCRAM-SHA-256), and Redis 8 (redis:8-alpine).


Why I redesigned the homelab database layer

In my first homelab iteration, I ran a shared MariaDB and Redis stack alongside scattered SQLite files inside individual app containers. As the number of services grew, three cracks showed up:

  1. No privilege isolation: Multiple web apps shared a single database user. One misconfigured container or leaked .env file could read or drop tables belonging to completely unrelated services.
  2. PostgreSQL as the modern self-hosted baseline: Tools I wanted for homelab v2—like LLDAP, Authelia, Gitea, and Outline—either require PostgreSQL or recommend it for JSONB, SCRAM-SHA-256 authentication, and predictable transaction semantics.
  3. Manual SQL bootstrapping: Every time I rebuilt the server or added a new service, I had to exec into the database container and hand-type CREATE USER and CREATE DATABASE statements. That process was easy to fat-finger and hard to reproduce.

For homelab v2, I standardized on a single PostgreSQL instance (with SCRAM-SHA-256 enforced) and Redis 8 (with AOF persistence), backed by an idempotent Bash script that creates isolated per-service roles and databases on demand.

ApproachMemory OverheadPrivilege IsolationRebuild / Backup Effort
Per-app DB containerHigh (N instances)Strong (separate processes)High (N backup jobs & upgrades)
Shared DB + single userLowPoor (blast radius spans all apps)Low, but risky
Shared Postgres + per-app role (v2)LowStrong (per-DB ownership)Low (single dump target + script)

When not to share a single database instance: Don’t consolidate workloads that require different PostgreSQL major versions, strict noisy-neighbor I/O isolation, or independent maintenance windows. In a multi-team production environment, separate instances per service are worth the extra cost; on a single-node homelab, per-service roles on one well-tuned instance hit the sweet spot.


Core database network topology

I never bind database ports to 0.0.0.0. Instead, PostgreSQL and Redis bind only to the host’s private management IP (for local admin tools if needed) and communicate with application containers over a dedicated external Docker bridge network named database_network.

flowchart TD
    subgraph Host["Docker Host"]
        subgraph NetDB["Isolated Network: database_network (external)"]
            PG["PostgreSQL<br/>(SCRAM-SHA-256 / Port 5432)"]
            RD["Redis 8-alpine<br/>(AOF Enabled / Port 6379)"]
        end

        Shell["create-databases.sh<br/>(docker exec psql)"]

        subgraph Consumers["Application Containers"]
            Auth["Authelia (DB: authelia)"]
            LL["LLDAP (DB: lldap)"]
            Git["Gitea (DB: gitea)"]
            Wiki["Outline (DB: outline)"]
        end
    end

    Shell -->|"Idempotent SQL"| PG
    Auth -->|"Dedicated Role"| PG
    Auth -->|"Session Store"| RD
    LL -->|"Dedicated Role"| PG
    Git -->|"Dedicated Role"| PG
    Wiki -->|"Dedicated Role"| PG
    Wiki -->|"Cache / Queue"| RD
  • Pre-created external network (database_network): Creating the network manually via docker network create database_network decouples its lifecycle from any single Compose stack. Restarting the database stack never orphans DNS links in dependent app stacks.
  • Least privilege: lldap_user, authelia_user, gitea_user, and outline_user each own only their respective database and cannot touch another service’s data.

Docker Compose stack configuration

Here is database/docker-compose.yaml. Every required secret uses Docker Compose’s :?required syntax so startup fails fast instead of silently booting with empty credentials.

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
# database/docker-compose.yaml
name: database

services:
  postgres:
    image: postgres:latest
    container_name: postgres
    restart: unless-stopped
    environment:
      TZ: Asia/Seoul
      POSTGRES_USER: ${POSTGRES_USER:?required}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?required}
      POSTGRES_DB: ${POSTGRES_DB:-postgres}
      POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256"
    ports:
      # Bind only to the private host IP to prevent public exposure
      - "${SERVER_IP:?required}:5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - database_network
    healthcheck:
      test:
        - CMD-SHELL
        - 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"'
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

  redis:
    image: redis:8-alpine
    container_name: redis
    restart: unless-stopped
    environment:
      TZ: Asia/Seoul
    command:
      - redis-server
      - --appendonly
      - "yes"
    ports:
      - "${SERVER_IP:?required}:6379:6379"
    volumes:
      - redis_data:/data
    networks:
      - database_network
    healthcheck:
      test:
        - CMD
        - redis-cli
        - ping
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

volumes:
  postgres_data:
  redis_data:

networks:
  database_network:
    external: true

Key configuration choices

  1. POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256": Forces salted SCRAM-SHA-256 challenge-response authentication during cluster initialization instead of legacy MD5 hashes.
  2. redis-server --appendonly yes: Turns on Append-Only File (AOF) persistence so Authelia sessions and Outline queues survive container restarts.
  3. Explicit healthchecks: Both pg_isready and redis-cli ping give operators and dependent scripts a reliable readiness signal instead of guessing with sleep.

Idempotent database provisioning with psql

PostgreSQL’s official image only creates one default database and superuser during initial boot. To provision isolated roles and databases for every homelab app—and make it safe to re-run whenever I add a new service—I wrote database/scripts/create-databases.sh.

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

# Move to the database directory relative to this script
cd "$(dirname "$0")/.."

# Load environment variables from .env
set -a
source .env
set +a

# Target databases, roles, and matching password env vars
DB_NAMES=(lldap authelia gitea outline)
DB_USERS=(lldap_user authelia_user gitea_user outline_user)
DB_PASS_VARS=(
  LLDAP_DB_PASSWORD
  AUTHELIA_DB_PASSWORD
  GITEA_DB_PASSWORD
  OUTLINE_DB_PASSWORD
)

for i in "${!DB_NAMES[@]}"; do
  db="${DB_NAMES[$i]}"
  user="${DB_USERS[$i]}"
  pass_var="${DB_PASS_VARS[$i]}"
  password="${!pass_var:?Missing $pass_var}"

  echo "==> Creating/checking: $db (User: $user)"

  docker exec \
    -e PGPASSWORD="$POSTGRES_PASSWORD" \
    -e TARGET_DB="$db" \
    -e TARGET_USER="$user" \
    -e TARGET_PASSWORD="$password" \
    postgres sh -c '
      psql -X -v ON_ERROR_STOP=1 \
        -U "$POSTGRES_USER" -d postgres \
        -v db="$TARGET_DB" \
        -v dbuser="$TARGET_USER" \
        -v dbpass="$TARGET_PASSWORD" <<'"'"'SQL'"'"'
SELECT format(
  '"'"'CREATE ROLE %I LOGIN PASSWORD %L'"'"',
  :'"'"'dbuser'"'"', :'"'"'dbpass'"'"'
)
WHERE NOT EXISTS (
  SELECT 1 FROM pg_roles WHERE rolname = :'"'"'dbuser'"'"'
)
\gexec

SELECT format(
  '"'"'CREATE DATABASE %I OWNER %I'"'"',
  :'"'"'db'"'"', :'"'"'dbuser'"'"'
)
WHERE NOT EXISTS (
  SELECT 1 FROM pg_database WHERE datname = :'"'"'db'"'"'
)
\gexec
SQL
    '
done

echo "==> All application databases are ready."

How \gexec achieves idempotency under the hood

PostgreSQL does not support CREATE ROLE IF NOT EXISTS or CREATE DATABASE IF NOT EXISTS in standard DDL. Instead, the script queries the system catalogs (pg_roles and pg_database) and uses format() with %I (identifier escaping) and %L (literal escaping) to generate the DDL statement only when the object is missing.

psql’s \gexec meta-command takes every column of every row returned by the previous query and executes it as a SQL statement. When the role or database already exists, the SELECT returns zero rows and \gexec does nothing—no duplicate-object errors, and safe quoting even if a password contains special characters.


Startup and verification

Create the external network first, bring up the containers, and run the provisioning script:

1
2
3
4
5
6
7
8
9
10
11
12
# 1. Create the shared external database network
docker network create database_network

# 2. Start PostgreSQL and Redis
docker compose up -d

# 3. Verify both containers report healthy
docker compose ps

# 4. Provision isolated per-service roles and databases
chmod +x scripts/create-databases.sh
./scripts/create-databases.sh

Verify that all four databases exist with the right owners:

1
docker exec -it postgres psql -U postgres -c "\l"

You should see lldap, authelia, gitea, and outline owned by lldap_user, authelia_user, gitea_user, and outline_user respectively. Re-running ./scripts/create-databases.sh should finish cleanly with exit code 0 and no errors.


Production caveats and checklist

Pin the PostgreSQL major version before upgrading: The snippet above uses postgres:latest for brevity, which works until a new major version (e.g., 17 → 18) drops and refuses to boot against an older PG_VERSION data directory. In daily operation, pin the major tag such as postgres:17 and plan pg_dumpall or pg_upgrade explicitly.

  • Password rotation: Because the script skips existing roles, rotating a password in .env won’t automatically update PostgreSQL. Run ALTER ROLE <user> WITH PASSWORD '...' explicitly when rotating secrets.
  • Redis authentication: If SERVER_IP is reachable from other machines on your LAN, add --requirepass to the Redis command or remove the host ports: binding altogether so only database_network containers can reach port 6379.
  • Pre-launch checklist:
    • database_network created as an external Docker bridge network
    • POSTGRES_INITDB_ARGS sets --auth-host=scram-sha-256
    • Ports bound only to private SERVER_IP (or omitted for container-only access)
    • create-databases.sh succeeds twice in a row with zero errors
    • Automated pg_dumpall backup scheduled off-host

With the core persistence tier in place, the next building block in homelab v2 is centralizing user accounts—see running LLDAP as a lightweight homelab directory service.

This post is licensed under CC BY 4.0 by the author.