Compose in Production
Is Compose "only for development"? No. Plenty of real services run on a single server with docker compose up -d: internal tools, small SaaS products, self-hosted apps, edge boxes, staging environments. It's simple, it's easy to reason about, and there's no cluster to operate. What you give up is everything a multi-host orchestrator provides: surviving a dead machine, spreading load across hosts, health-gated rolling updates.
This lesson is about doing the single-host case well: a production override, images that are built once and pinned, safe deploys, logs, backups and a server that comes back after a reboot.
When Compose is (and isn't) enough
| Compose on one host is fine when… | Look at Swarm/Kubernetes when… |
|---|---|
| a few minutes of downtime during a host failure is acceptable | you need to survive losing a machine |
| one server can carry the load | you need more capacity than one host |
| deploys can have a few seconds of restart | you need zero-downtime rolling updates as standard |
| one team operates it | many teams share the platform |
The production override
Keep the base file environment-neutral and put production decisions in compose.prod.yaml:
# $ docker compose -f compose.yaml -f compose.prod.yaml config
services:
api:
build: .
image: ghcr.io/acme/api:${API_TAG:-dev}
ports: ["5000:5000"]
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:5000/health"]
interval: 10s
# --- compose.prod.yaml
services:
api:
build: !reset null
image: ghcr.io/acme/api:${API_TAG:?API_TAG must be set for production}
pull_policy: always
ports: !reset []
restart: unless-stopped
stop_grace_period: 30s
read_only: true
tmpfs: ["/tmp:size=64m"]
deploy:
resources:
limits: {cpus: "1.0", memory: 512M}
logging:
driver: local
options: {max-size: 20m, max-file: "5"}
# --- .env
API_TAG=3.1.4name: demo
services:
api:
deploy:
resources:
limits:
cpus: 1
memory: "536870912"
restart: unless-stopped
image: ghcr.io/acme/api:3.1.4
logging:
driver: local
options:
max-file: "5"
max-size: 20m
networks:
default: null
pull_policy: always
read_only: true
stop_grace_period: 30s
tmpfs:
- /tmp:size=64m
healthcheck:
test:
- CMD
- wget
- -qO-
- http://localhost:5000/health
interval: 10s
networks:
default:
name: demo_default
What each production setting does:
build: !reset null: production never builds. Images are built once, in CI, tested, pushed to a registry, and the server only pulls them. "Works on my machine" builds on the server are how untested code reaches users.${API_TAG:?…}: the version must be set explicitly. No accidentallatest.pull_policy: always:upchecks the registry for the tag. (Pinning a digest,image: ghcr.io/acme/api@sha256:…, is stricter still: the bytes can never change.)ports: !reset []: the API is not published directly; a reverse proxy in front terminates TLS.restart: unless-stopped: containers come back after crashes and after a reboot of the Docker daemon. See Restart Policies.stop_grace_period: 30s: time between SIGTERM and SIGKILL for in-flight requests to finish (default 10 s).read_only+tmpfs, resource limits and rotated logs: covered in Bind Mounts & tmpfs, Scaling & Resources and Logs & Debugging.
Without API_TAG the production file refuses to render, which is exactly what you want:
# $ docker compose -f compose.yaml -f compose.prod.yaml config
services:
api:
image: ghcr.io/acme/api:${API_TAG:-dev}
# --- compose.prod.yaml
services:
api:
image: ghcr.io/acme/api:${API_TAG:?API_TAG must be set for production}error while interpolating services.api.image: required variable API_TAG is missing a value: API_TAG must be set for production
TLS and the front door
A reverse proxy service owns ports 80/443, gets certificates from Let's Encrypt and forwards to the app by service name. Caddy is a compact choice:
services:
proxy:
image: caddy:2.10
restart: unless-stopped
ports: ["80:80", "443:443", "443:443/udp"] # udp for HTTP/3
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data # certificates: must persist!
depends_on:
api: {condition: service_healthy}
volumes:
caddy_data:# Caddyfile
shop.example.com {
reverse_proxy api:5000
}Deploying a new version
A deploy script on the server, or run over SSH from CI:
#!/usr/bin/env bash
set -euo pipefail
export API_TAG="$1" # e.g. 3.1.5
COMPOSE="docker compose -f compose.yaml -f compose.prod.yaml"
$COMPOSE config -q # fail early on a broken file
$COMPOSE pull # download before touching anything
$COMPOSE up -d --no-build --remove-orphans --wait --wait-timeout 120
docker image prune -f # drop old, unused images--wait makes the script fail if the new containers don't become healthy, so CI shows a red deploy instead of a silent outage. --remove-orphans deletes containers of services you removed from the file.
Compose recreates a service by stopping the old container, then starting the new one, so each deploy has a short gap. A model of the timeline and the rollback decision:
def deploy(old, new, healthy_after, timeout=120, stop_grace=5, start=3):
t, log = 0, []
log.append((t, f"pull {new} (old {old} keeps serving)")); t += 20
log.append((t, f"stop {old} (SIGTERM, up to {stop_grace}s)")); t += stop_grace
log.append((t, f"start {new}")); t += start
if healthy_after is not None and healthy_after <= timeout:
t += healthy_after
log.append((t, f"{new} healthy -> deploy ok"))
downtime = stop_grace + start + healthy_after
else:
t += timeout
log.append((t, f"{new} not healthy after {timeout}s -> --wait fails, script redeploys {old}"))
t += start + 5
log.append((t, f"{old} healthy again"))
downtime = stop_grace + start + timeout + start + 5
for when, what in log:
print(f" t={when:>3}s {what}")
print(f" unavailable for about {downtime}s")
print("deploy 3.1.5:")
deploy("3.1.4", "3.1.5", healthy_after=6)
print("deploy 3.1.6 (broken migration):")
deploy("3.1.5", "3.1.6", healthy_after=None)deploy 3.1.5:
t= 0s pull 3.1.5 (old 3.1.4 keeps serving)
t= 20s stop 3.1.4 (SIGTERM, up to 5s)
t= 25s start 3.1.5
t= 34s 3.1.5 healthy -> deploy ok
unavailable for about 14s
deploy 3.1.6 (broken migration):
t= 0s pull 3.1.6 (old 3.1.5 keeps serving)
t= 20s stop 3.1.5 (SIGTERM, up to 5s)
t= 25s start 3.1.6
t=148s 3.1.6 not healthy after 120s -> --wait fails, script redeploys 3.1.5
t=156s 3.1.5 healthy again
unavailable for about 136s
Those seconds of unavailability are usually fine for internal tools. If they aren't, run two replicas behind the proxy and update them one at a time (docker compose up -d --no-deps --scale api=2 … scripting gets fiddly quickly), or use Swarm, whose update_config with order: start-first does exactly this for you.
Rollback = deploy the previous tag: ./deploy.sh 3.1.4. Keep the last few tags in the registry, and make database migrations backward compatible so the old version still runs against the new schema.
Surviving reboots
With restart: unless-stopped (or always) and the Docker service enabled at boot (systemctl enable docker), containers come back on their own. Some teams prefer a systemd unit that runs the deploy command, so the project is managed like any other service:
# /etc/systemd/system/shop.service
[Unit]
Description=Shop (Docker Compose)
Requires=docker.service
After=docker.service network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/shop
EnvironmentFile=/srv/shop/release.env
ExecStart=/usr/bin/docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
ExecStop=/usr/bin/docker compose -f compose.yaml -f compose.prod.yaml down
[Install]
WantedBy=multi-user.targetBackups and data
The host is a single point of failure, so its data must be copied elsewhere: scheduled pg_dump (a backup service with a cron image, or a host cron job running docker compose exec -T db pg_dump …) shipped to object storage, plus a tested restore procedure. Volumes are on the host's disk; if the disk dies, only off-host backups help.
Production checklist
| Area | Check |
|---|---|
| Images | built in CI, pinned tag or digest, no build: in prod |
| Config | docker compose … config -q passes; required variables use :? |
| Secrets | files or secrets, not in Git, not in images (see Compose Security) |
| Health | healthchecks on every long-running service; up --wait in deploys |
| Restart | restart: unless-stopped, Docker enabled at boot |
| Resources | memory limits on every service, log rotation |
| Network | only the proxy publishes ports; databases on an internal network |
| Data | off-host backups, tested restore |
| Observability | logs shipped off-host, basic metrics and an uptime check |
Learn more: Compose in CI · Compose Security · From Compose to Swarm · Docker Best Practices
Test yourself
Why does the production override use build: !reset null?
- Builds are slow
- Production should only run images built and tested in CI, never build on the server
- Compose can't build in production
- To save disk space
What does docker compose up -d --wait add to a deploy script?
- A fixed delay
- It fails if services don't become running/healthy, so a bad deploy is noticed
- Zero-downtime updates
- Automatic rollback
Which statement about updates with plain Compose is true?
- They are always zero-downtime
- A service is recreated by stopping the old container and starting the new one, so there's a short gap
- Compose does rolling updates across hosts
- Compose keeps both versions running