Docker Compose for production: patterns that survive reboots
The differences between a hobby docker-compose.yml and one you can leave alone for six months: restart policies, healthchecks, named volumes, secrets, resource limits, log rotation, and the dependency ordering that's correct on the first start.
The pattern, end to end
Below is a complete production Compose file for a generic web app (replace with your image) sitting in front of Postgres and Redis. We'll walk through each block and explain the reasoning.
name: myapp
services:
app:
image: ghcr.io/example/myapp:1.4.2
restart: unless-stopped
ports:
- "127.0.0.1:8080:8080"
environment:
DATABASE_URL: postgres://app:${DB_PASSWORD}@postgres:5432/app
REDIS_URL: redis://redis:6379/0
APP_SECRET_KEY: ${APP_SECRET_KEY}
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/health"]
interval: 30s
timeout: 5s
retries: 5
start_period: 30s
deploy:
resources:
limits:
memory: 512M
cpus: "1.0"
logging:
driver: json-file
options:
max-size: "10m"
max-file: "5"
read_only: true
tmpfs:
- /tmp
- /run
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE
security_opt:
- no-new-privileges:true
postgres:
image: postgres:16.4-alpine
restart: unless-stopped
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: app
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app"]
interval: 10s
timeout: 5s
retries: 5
deploy:
resources:
limits:
memory: 512M
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
redis:
image: redis:7-alpine
restart: unless-stopped
command: ["redis-server", "--maxmemory", "128mb", "--maxmemory-policy", "allkeys-lru"]
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
deploy:
resources:
limits:
memory: 192M
volumes:
postgres_data:
Pinned image tags
Pin to a specific version (postgres:16.4-alpine), not postgres:16 or postgres:latest. With latest or a floating major tag, a docker compose pull can change the image under you and the next restart may load a different version of the database with breaking config changes. Pinning makes upgrades a deliberate edit, not a surprise.
Restart policy
Use restart: unless-stopped, not restart: always. The difference: always restarts containers you manually stopped after a daemon restart. unless-stopped respects your intent. In production you want the latter.
Healthchecks
Without healthchecks, Docker considers a container "running" if its PID 1 exists. A wedged Postgres process or a deadlocked app server satisfies that. Add a meaningful probe — for HTTP services hit a /health endpoint; for databases use the vendor's readiness check (pg_isready, redis-cli ping, mysqladmin ping).
The start_period matters: it's a grace window during which failing healthchecks don't count against the restart counter. Set it to the actual startup time of the service. Otherwise Compose can flap a container that was just slow to boot.
Dependencies with conditions
The default depends_on: [postgres] only enforces start order, not readiness. Your app launches while Postgres is still initializing and crashes. With condition: service_healthy, Compose waits until the dependency reports healthy. This single line removes a class of "first start is flaky" bugs.
Bind to 127.0.0.1, not 0.0.0.0
The "127.0.0.1:8080:8080" notation exposes the port only to localhost. Combined with Nginx (or Traefik, or Caddy) terminating TLS, this is the safe default: nothing on this host is reachable on a non-loopback IP unless you explicitly put a reverse proxy in front.
If you ever see a Compose file with "5432:5432" for Postgres on a public VPS, that's a database open to the internet. Brute-force attempts on port 5432 show up in the log within hours.
Secrets via .env, mode 600
Generate strong values and reference them with ${VAR} substitution:
cat > .env <<EOF
DB_PASSWORD=$(openssl rand -base64 32)
APP_SECRET_KEY=$(openssl rand -base64 32)
EOF
chmod 600 .env
Never commit .env to git; add it to .gitignore. The Compose file itself is safe to commit — it has no secrets in it.
For multi-stage setups, Docker Compose also supports secrets: backed by files. The env-var pattern is simpler and good enough for the vast majority of self-hosted projects.
Named volumes vs bind mounts
For data that's purely "the application's state" (Postgres data dir, Redis dumps, an app's upload directory), use named volumes:
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
For data you want to edit from the host (config files, content directories), use bind mounts:
volumes:
- ./config/nginx.conf:/etc/nginx/nginx.conf:ro
- ./content:/var/www/html
The common bug with bind mounts is UID mismatch: if the container runs as UID 1000 and the host directory is owned by root, the container can't write to it. Named volumes avoid the problem entirely.
Resource limits
On a multi-service host, a runaway container that eats all RAM will kill its neighbours. The Linux OOM killer is not gentle. Add deploy.resources.limits on every service:
deploy:
resources:
limits:
memory: 512M
cpus: "1.0"
The deploy: key was originally a Swarm thing, but the limits are honored by plain Compose too.
Log rotation
Add per-service log limits in the Compose file and a global default in /etc/docker/daemon.json (see Docker install guide). The per-service setting wins. Verbose services get more retained logs; quiet services get fewer.
Container hardening
The app service in the example uses four hardening directives:
read_only: true— the container's filesystem is mounted read-only. The app gets writabletmpfsfor/tmpand/run. Stops a compromised process from persisting anything on disk.cap_drop: [ALL]+cap_add: [NET_BIND_SERVICE]— drops every Linux capability and adds back only the one needed to bind to a low-numbered port. SkipNET_BIND_SERVICEif your app binds to a high port.security_opt: ["no-new-privileges:true"]— child processes cannot escalate privileges through setuid binaries.
These cost nothing and meaningfully shrink the attack surface. Full hardening checklist in Docker security hardening.
Upgrade workflow
cd ~/myapp
# Edit docker-compose.yml: bump image tag, e.g. 1.4.2 -> 1.4.3
docker compose pull
docker compose up -d
docker compose ps # confirm both healthy
docker compose logs -f app # spot-check
Rollback: revert the tag, rerun the same three commands. The named volumes preserve data across image swaps within a major version.
The "name:" top-level field
name: myapp at the top sets the Compose project name explicitly, instead of inferring it from the directory name. Volumes get the prefix myapp_. This matters when you move the project to a different directory — without an explicit name, Compose may create new (empty) volumes because the prefix changed.
Multi-host vs multi-container
Docker Compose is designed for a single host. For multi-host you'd reach for Swarm, Nomad, or Kubernetes. Most self-hosted projects never need that — a single 4-8 GB VPS handles a surprising amount of traffic with the patterns above. If you're moving past one host, that's its own decision; don't pre-optimize.
VPS for a multi-service Docker host?
A 4 GB Inferno plan ($7.99/mo) runs the example stack above plus another similar one with headroom. Eight EU + Asia locations, NVMe, DDoS-included on every tier.
What to do next
- Harden the Docker host — daemon settings, image scanning, rootless mode.
- Add Traefik in front for automatic TLS and container discovery.
- Watchtower for opt-in automatic image updates.
- Uptime Kuma as a self-hosted external monitor.
Author: Riku Lehtinen — Linux sysadmin, Tampere. Last tested: 2026-05-22 on Docker CE 27.3, Compose plugin 2.30.