← All notes

DevOps

Self-Hosted Dev Infrastructure with Docker Compose

Per-project service duplication wastes time and breaks isolation. Build one shared infra stack with Traefik, PostgreSQL, Redis, MinIO, and Mailpit that every app joins over a named Docker network.

Published
Reading
8 min
Author
Fidelis Uwem Joseph
Series · Part 1 of 4Self-hosted Infrastructure
  1. Self-Hosted Dev Infrastructure with Docker Compose
  2. Traefik v3: Routing Multiple Docker Apps on One Server
  3. Traefik v3: Automatic Routing, TLS, and Middleware for Docker
  4. Docker on a VPS: UFW, Port Bindings, and SSH Tunnels

Series overviewPart 2 →

Most dev setups run a separate Postgres, Redis, and MinIO for every project. Six containers doing the same job, different passwords, none of them shared. This post replaces that with one docker-compose.yml: a shared infra stack on a named Docker network that any app can join without owning or duplicating the services. By the end you’ll have Traefik routing traffic, PostgreSQL and Redis running internally, MinIO handling object storage, and Mailpit catching all outbound email. Assumed knowledge: Docker basics and .env files.

Prerequisites

  • Docker Engine 24+
  • Docker Compose v2
  • Linux server or local machine (Ubuntu 22.04+ used throughout)
  • Traefik v3 already running as your reverse proxy

Background

The standard approach redeclares shared services in every project’s Compose file. Tear down one app and Postgres stops. Start a new project and you reconfigure the same variables again.

The fix: one named network (infra_net) owns all shared services. App stacks declare it as external: true and connect by Docker DNS name (postgres:5432, redis:6379) without touching host ports. The infra stack runs independently of any app. Apps attach to it, they don’t own it.


Implementation

1. Define the shared network and volumes

The name: infra_net field is required. Without it, Docker prepends the Compose project directory name to the network, and every external: true reference in your app stacks fails silently.

docker-compose.yml
networks:
infra_net:
driver: bridge
name: infra_net
volumes:
postgres_data:
redis_data:
minio_data:
traefik_logs:
mailpit_data:

2. Configure Traefik

docker-compose.yml
traefik:
image: traefik:v3.2
container_name: traefik
restart: unless-stopped
ports:
- "0.0.0.0:80:80"
- "127.0.0.1:8080:8080"
- "0.0.0.0:8005:8005"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./traefik/traefik.yml:/etc/traefik/traefik.yml:ro
- traefik_logs:/logs
networks:
- infra_net
labels:
- "traefik.enable=false"

Port 8080 (dashboard) is bound to 127.0.0.1 only. Access it via SSH tunnel. Port 8005 is the public Mailpit entrypoint.

traefik.enable=false prevents Traefik from creating a route to its own container. Without it, a self-referential router appears in the dashboard.

3. Add PostgreSQL

docker-compose.yml
postgres:
image: postgres:16-alpine
container_name: postgres
restart: unless-stopped
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- infra_net
ports:
- "127.0.0.1:5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 1
start_period: 10s

start_period: 10s gives Postgres time to initialize before retries start counting. pg_isready checks whether the server accepts connections without running a query.

The host port (127.0.0.1:5432) exists for local tooling only: psql, DBeaver, pgAdmin. App containers connect to postgres:5432 over infra_net with no host port involved.

4. Add Redis

docker-compose.yml
redis:
image: redis:7-alpine
container_name: redis
restart: unless-stopped
command: >
redis-server
--requirepass ${REDIS_PASSWORD}
--appendonly yes
--appendfsync everysec
volumes:
- redis_data:/data
networks:
- infra_net
ports:
- "127.0.0.1:6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
interval: 10s
timeout: 5s
retries: 1

--appendonly yes with --appendfsync everysec makes writes durable to within one second on crash. Without it, every container restart clears Redis entirely.

If Redis is purely an ephemeral cache with no sessions or task queues, drop the command block. The default configuration has lower overhead with no persistence.

5. Add MinIO

docker-compose.yml
minio:
image: minio/minio:latest
container_name: minio
restart: unless-stopped
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
volumes:
- minio_data:/data
networks:
- infra_net
ports:
- "127.0.0.1:9000:9000"
- "127.0.0.1:9001:9001"
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 15s
timeout: 5s
retries: 1
start_period: 15s

--console-address ":9001" pins the Console to a fixed port. Without it, MinIO binds the Console to a random port on every restart. The S3 API is always on 9000.

6. Add Mailpit

docker-compose.yml
mailpit:
image: axllent/mailpit:latest
container_name: mailpit
restart: unless-stopped
ports:
- "127.0.0.1:1025:1025"
environment:
MP_SMTP_AUTH_ACCEPT_ANY: 1
MP_SMTP_AUTH_ALLOW_INSECURE: 1
MP_UI_AUTH: ${MAILPIT_UI_AUTH}
MP_LABEL: ${MAILPIT_LABEL:-Sofrosyn Mail}
MP_DATABASE: /data/mailpit.db
volumes:
- mailpit_data:/data
networks:
- infra_net
labels:
- "traefik.enable=true"
- "traefik.http.routers.mailpit.rule=PathPrefix(`/`)"
- "traefik.http.routers.mailpit.entrypoints=mail-server"
- "traefik.http.services.mailpit.loadbalancer.server.port=8025"
healthcheck:
test: ["CMD", "/mailpit", "readyz"]
interval: 15s
timeout: 5s
retries: 3
start_period: 10s

MP_SMTP_AUTH_ACCEPT_ANY: 1 accepts any SMTP credentials. This is intentional: you don’t want email flows failing in dev because credentials don’t match. MP_UI_AUTH applies to the Web UI only, not SMTP.

7. Write the environment file

.env
# Postgres
POSTGRES_USER=admin
POSTGRES_PASSWORD=changeme
POSTGRES_DB=postgres
# Redis
REDIS_PASSWORD=changeme
# MinIO
MINIO_ROOT_USER=minioadmin
MINIO_ROOT_PASSWORD=changeme
# Mailpit
MAILPIT_UI_AUTH=admin:changeme sofrosyn:changeme
MAILPIT_LABEL=Sofrosyn Mail

Add .env to .gitignore before your first commit.

8. Attach an app stack

app/docker-compose.yml
networks:
infra_net:
external: true
services:
api:
networks:
- infra_net
environment:
DATABASE_URL: postgresql://admin:changeme@postgres:5432/postgres
REDIS_URL: redis://:changeme@redis:6379/0
MINIO_ENDPOINT: http://minio:9000
SMTP_HOST: mailpit
SMTP_PORT: 1025

Container names (postgres, redis, minio, mailpit) are the DNS hostnames inside infra_net. No IP addresses, no host port forwarding.


Testing and Verification

Bring the stack up:

terminal
docker compose up -d

Check that all services reach healthy status:

terminal
docker compose ps

Expected output:

NAME IMAGE STATUS
traefik traefik:v3.2 running
postgres postgres:16-alpine running (healthy)
redis redis:7-alpine running (healthy)
minio minio/minio:latest running (healthy)
mailpit axllent/mailpit:latest running (healthy)

If a service shows starting, wait 15 seconds and re-check. If it stays stuck, inspect the logs:

terminal
docker compose logs postgres --tail 20

Verify Traefik has registered the Mailpit route:

terminal
curl -s http://localhost:8080/api/http/routers | jq '.[].name'
# "mailpit@docker"

Open http://your-server:8005. The Mailpit UI should prompt for the credentials from MAILPIT_UI_AUTH.


Pitfalls


Production Considerations

Move credentials out of .env before this stack handles real data. Docker Secrets, AWS SSM Parameter Store, and HashiCorp Vault all integrate with Compose. .env files in any repository, including private ones, are how credentials get leaked.

Add TLS to Traefik via a certificatesResolvers block in traefik.yml. Traefik handles Let’s Encrypt issuance and renewal automatically. There’s no reason to run plain HTTP once you have a domain pointed at the server.

Set MP_MAX_MESSAGES on Mailpit. The SQLite database grows without bound under sustained email traffic. A cap of 500 to 1000 messages is enough for most staging setups.

Enable pg_stat_statements before running any real query load:

docker-compose.yml
postgres:
command: postgres -c shared_preload_libraries=pg_stat_statements

Without it, identifying slow queries requires guesswork. With it, per-query execution stats are immediately available in pg_stat_statements.


Going deeper

A shared stack is only better than per-project containers if the projects stay out of each other’s way. This section covers isolation between apps, start-up order across stacks, backups you have actually restored, upgrades and resource limits.

One database and role per app

Step 8 connects every app as admin to the postgres database. That means any app can read or drop any other app’s tables, and one leaked connection string exposes everything. Give each app its own database owned by its own role:

infra/postgres/new-app.sql
-- run with: psql -v app=billing -v pass="'s3cret'" -f new-app.sql
CREATE ROLE :"app" LOGIN PASSWORD :pass;
CREATE DATABASE :"app" OWNER :"app";
REVOKE ALL ON DATABASE :"app" FROM PUBLIC;
Makefile
new-app-db:
docker compose exec -T postgres psql -U $(POSTGRES_USER) -d postgres \
-v app=$(NAME) -v pass="'$(PASS)'" < infra/postgres/new-app.sql
terminal
make new-app-db NAME=billing PASS="$(openssl rand -base64 24)"

REVOKE ... FROM PUBLIC stops other roles from even connecting to the database. The app’s URL becomes postgresql://billing:...@postgres:5432/billing, and the superuser password stays out of every app’s environment.

Scripts in /docker-entrypoint-initdb.d are the usual place for setup SQL, but they only run when the data volume is empty. They are good for the first app and useless for the fifth, which is why the Makefile target runs against the live server instead.

Redis 6 and later can do the same with ACL users, each limited to its own key prefix:

terminal
docker compose exec redis redis-cli --user default --pass "$REDIS_PASSWORD" \
ACL SETUSER billing on '>billing-pass' '~billing:*' '&billing:*' +@all -@dangerous

~billing:* limits keys, &billing:* limits pub/sub channels, and -@dangerous removes commands like FLUSHALL and CONFIG. ACL users created this way live in memory. Persist them with an ACL file (--aclfile /data/users.acl and ACL SAVE), or they disappear on restart.

Start-up order across stacks

Inside one Compose file, depends_on with condition: service_healthy waits for Postgres before starting the API. Across stacks it does nothing: an app’s Compose project cannot depend on a service defined in the infra project. After a server reboot, both projects start at the same time, and the app tries to connect before Postgres is ready.

The robust fix is in the app, not in Compose: retry the first connection with backoff. Most drivers make this a few lines:

app/db.py
import time
import psycopg
def connect_with_retry(url: str, attempts: int = 10) -> psycopg.Connection:
for i in range(attempts):
try:
return psycopg.connect(url, connect_timeout=3)
except psycopg.OperationalError:
time.sleep(min(2 ** i, 15))
raise RuntimeError("database not reachable")

restart: unless-stopped on the app container is a second line of defence: if the app exits because the database is not ready, Docker starts it again. Relying on that alone works, but fills the logs with crash traces after every reboot.

Back up, then prove you can restore

A named volume survives docker compose down. It does not survive a failed disk, a deleted server or docker volume prune. A small backup service can dump every database on a schedule:

docker-compose.yml
pg-backup:
image: postgres:16-alpine
restart: unless-stopped
environment:
PGHOST: postgres
PGUSER: ${POSTGRES_USER}
PGPASSWORD: ${POSTGRES_PASSWORD}
volumes:
- ./backups:/backups
entrypoint: >
/bin/sh -c 'while true; do
pg_dumpall | gzip > /backups/all-$$(date +%F).sql.gz;
find /backups -name "all-*.sql.gz" -mtime +7 -delete;
sleep 86400;
done'
networks:
- infra_net

This keeps seven daily dumps on the host. Copy ./backups off the server (rclone, mc mirror to the MinIO bucket of another machine, or your provider’s object storage), because a backup on the same disk shares the same failures.

A backup you have never restored is a hope, not a backup. Restore into a throwaway container once, and again whenever the setup changes:

terminal
docker run --rm -d --name restore-test -e POSTGRES_PASSWORD=test postgres:16-alpine
sleep 5
gunzip -c backups/all-$(date +%F).sql.gz | docker exec -i restore-test psql -U postgres
docker exec restore-test psql -U postgres -c '\l' # every app database should be listed
docker rm -f restore-test

For MinIO, see the mc mirror section of the MinIO post. Redis with appendonly yes can be backed up by copying /data while it runs, but treat Redis as rebuildable: anything you cannot afford to lose belongs in Postgres.

Upgrade without surprises

Two images in this stack use latest (MinIO and Mailpit). docker compose pull will move them to whatever was published that day, including breaking changes. Pin release tags and upgrade on purpose.

Postgres needs extra care. Minor versions (16.3 to 16.4) are drop-in: pull and restart. Major versions (16 to 17) store data in an incompatible format, and a postgres:17 container pointed at a version 16 volume refuses to start. The simple path for a dev stack is dump and restore:

terminal
docker compose exec -T postgres pg_dumpall -U "$POSTGRES_USER" > upgrade.sql
docker compose down postgres
docker volume rm infra_postgres_data # after confirming upgrade.sql is complete
# change the image to postgres:17-alpine, then:
docker compose up -d postgres
docker compose exec -T postgres psql -U "$POSTGRES_USER" -d postgres < upgrade.sql

The volume name is prefixed with the Compose project name. Check it with docker volume ls before removing anything.

Keep one service from starving the rest

On a shared server, one runaway service affects every app. Cap memory per container, and give Redis its own limit and eviction policy so it degrades as a cache instead of crashing:

docker-compose.yml
redis:
command: >
redis-server
--requirepass ${REDIS_PASSWORD}
--appendonly yes
--maxmemory 256mb
--maxmemory-policy allkeys-lru
mem_limit: 384m
postgres:
mem_limit: 1g

Leave headroom between Redis’s maxmemory and the container limit: Redis needs memory beyond the dataset for buffers and AOF rewrites. Use noeviction instead of allkeys-lru if Redis also holds Celery queues or sessions, because evicting a queued task silently loses work.

Keep secrets out of the process list

The Redis health check passes the password with -a, which makes it visible to anyone who can run ps or docker inspect on the host. redis-cli reads the same password from an environment variable:

docker-compose.yml
redis:
environment:
REDISCLI_AUTH: ${REDIS_PASSWORD}
healthcheck:
test: ["CMD", "redis-cli", "ping"]

While you are there, raise retries from 1 to 3 on each health check. With a single retry, one slow response during a busy moment marks the service unhealthy.

Troubleshooting

SymptomLikely causeFix
App fails to connect after a rebootStacks start together, depends_on cannot cross projectsRetry the first connection with backoff
network infra_net not foundInfra stack not running, or network created without name:Start infra first, set name: infra_net
Postgres will not start after an image changeMajor version mismatch with the data volumeDump, recreate the volume, restore
One app can read another’s dataShared superuser connectionPer-app role and database, Redis ACL users
Redis killed by the OOM killerNo maxmemorySet maxmemory below the container limit
Password visible in ps outputredis-cli -a in the health checkUse REDISCLI_AUTH

Wrapping Up

You now have one shared infra stack that any app attaches to via infra_net. One docker compose up -d gives you a database, cache, object storage, and email testing with no cloud dependencies and no per-project duplication.

Next: lock down the network exposure before anything else hits the internet.