Overview and What You Will Learn
Docker Compose is a reasonable production tool for a single host: small teams, internal tools, staging, and low-risk services. It has no multi-host scheduling, self-healing across machines, or rolling updates, so it is the wrong foundation for business-critical services that must survive a server failure.
In this lab you will:
- Decide honestly whether Compose fits your workload.
- Build a production override with restart policies, log rotation, resource limits, and secrets.
- Put a reverse proxy in front and stop exposing internal ports.
- Update and roll back a service safely.
- Back up PostgreSQL and recognise the signs that you have outgrown Compose.
Why This Matters in Production
Many teams run real workloads on one well-managed VM with Compose, and that is a sound choice when the cost of brief downtime is low. The failures come from pretending Compose offers guarantees it does not: if the host dies, every container dies with it, and a failed restart means someone logs in and fixes it by hand.
Choosing deliberately avoids both extremes. Teams at companies such as Zerodha and Razorpay run large platforms on orchestrators, but plenty of internal dashboards, staging stacks, and early-stage products at the same kind of company run happily on a single host. The skill is matching the tool to the failure cost.
Core Principles
A production Compose host is a small, well-defined system: a proxy faces the internet, application containers sit on a private network, and data lives in named volumes that are backed up.
Use this checklist to decide whether Compose fits:
- One host is acceptable. If the machine fails, you can restore or recreate it within your allowed downtime.
- Brief restarts are acceptable. Updating a container causes a short interruption.
- Manual scaling is enough. Traffic fits one machine, or you can resize the VM.
- A small team operates it. There is no need for platform-level self-service.
If any answer is no, plan for Kubernetes or a managed container service instead.
Detailed Step-by-Step Practical Lab
How to Layer a Production Override
Keep shared definitions in compose.yaml and put production-only settings in compose.prod.yaml.
services: api: image: registry.example.com/payment-api:${IMAGE_TAG:?set IMAGE_TAG} restart: unless-stopped ports: !reset [] # no host port: only nginx reaches it env_file: - .env.production logging: driver: json-file options: max-size: "100m" max-file: "3" deploy: resources: limits: cpus: "1.5" memory: 512M healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/health"] interval: 30s timeout: 5s retries: 3 start_period: 15s nginx: image: nginx:1.27-alpine restart: unless-stopped ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - ./nginx/certs:/etc/nginx/certs:ro depends_on: api: condition: service_healthy logging: driver: json-file options: max-size: "50m" max-file: "3" postgres: restart: unless-stopped ports: !reset [] # never publish the database secrets: - db_password environment: POSTGRES_PASSWORD_FILE: /run/secrets/db_password logging: driver: json-file options: max-size: "50m" max-file: "5" secrets: db_password: file: /opt/payment-api/secrets/db_password.txtThe !reset [] tag removes a list inherited from the base file, which Compose would otherwise merge by appending. It requires a recent Compose v2 release, so confirm with docker compose version.
# Avoid repeating -f flagsexport COMPOSE_FILE=compose.yaml:compose.prod.yaml # Inspect exactly what will rundocker compose configHow to Start Services on Boot
Containers with restart: unless-stopped come back after a host reboot as long as the Docker service itself is enabled.
sudo systemctl enable dockersudo rebootdocker compose ps # services return without manual actionHow to Update a Service
Compose recreates a container when its image or configuration changes. This causes a short interruption, so plan updates for a quiet window.
cd /opt/payment-apised -i 's/^IMAGE_TAG=.*/IMAGE_TAG=a3f8c12/' .envdocker compose pull apidocker compose up -d --no-deps --wait --wait-timeout 90 api--no-deps leaves PostgreSQL and nginx untouched, and --wait returns only when the new container is healthy.
How to Roll Back
Immutable image tags make rollback a configuration change.
sed -i 's/^IMAGE_TAG=.*/IMAGE_TAG=9b21d4e/' .env # previous known-good tagdocker compose up -d --no-deps --wait apidocker inspect payment-platform-api-1 --format '{{.Config.Image}}'How to Get Close to Zero Downtime
Compose has no rolling update. If a short interruption is not acceptable, you can run two copies of the service behind the proxy and recreate them one at a time, or place a proxy such as Traefik in front that routes only to healthy containers. Be realistic: that is a workaround for a single host, and it does not protect you from the host itself failing.
How to Back Up PostgreSQL
A volume is not a backup. Dump the database on a schedule and copy the file off the host.
# Logical backup from inside the containerdocker compose exec -T postgres pg_dump -U api_user -d payments -Fc > /backups/payments-$(date +%F).dump # Copy to object storage (example for AWS S3 in Mumbai)aws s3 cp /backups/payments-$(date +%F).dump s3://acme-prod-backups/payments/ --region ap-south-1 # Restore into an empty databasedocker compose exec -T postgres pg_restore -U api_user -d payments --clean < /backups/payments-2025-01-15.dumpTest restores regularly. An untested backup is a hope, not a recovery plan.
How to Know When to Leave Compose
Move to Kubernetes or a managed service when you need survival of a node failure, independent autoscaling, rolling deployments across hosts, or many teams deploying separately. The comparison below summarises the gap.
| Need | Compose on one host | Kubernetes |
|---|---|---|
| Survive a host failure | No | Yes, pods reschedule |
| Rolling updates | Manual workaround | Built in |
| Autoscaling | No | HPA and cluster autoscaler |
| Operational cost | Low | Significant |
Production Best Practices & Common Pitfalls
- Use
unless-stopped, notalways:alwaysstarts a container again after a daemon restart even if you stopped it on purpose for maintenance. - Rotate logs: the default
json-filedriver does not rotate, so setmax-sizeandmax-fileor a full disk will take down every container. - Do not publish database or cache ports: keep them on the private network and expose only the proxy.
- Pin image tags: use version or commit tags so deploys and rollbacks are deterministic.
- Set resource limits: one runaway container should not starve the rest of the host.
- Monitor the host: disk, memory, and container restart counts need alerts, because Compose will not page you.
- Use secrets or a manager: keep passwords out of the Compose file and out of git.
TipExport
COMPOSE_FILE=compose.yaml:compose.prod.yamlin the deployment user's shell profile so nobody runs a command against the wrong file set by accident.
RememberCompose offers no failover. If the host goes down, everything on it goes down, so your recovery plan is restoring the host and its backups.
Common MistakeTreating a single-host Compose deployment as highly available. A crashed host, a full disk, or a failed restart is an outage until someone fixes it manually.
SecurityDo not expose PostgreSQL, Redis, or the Docker socket to the internet. Publish only ports 80 and 443 through the reverse proxy, and restrict SSH to known addresses.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker compose pull <svc> |
Fetch the new image for a service |
docker compose up -d --no-deps --wait <svc> |
Recreate one service and wait for health |
docker compose config |
Show the merged production configuration |
docker compose logs --tail=100 <svc> |
Recent logs |
docker system df |
Disk used by images, volumes, and cache |
docker inspect <name> --format '{{.RestartCount}}' |
Detect crash loops |
| Problem | Likely cause | Fix |
|---|---|---|
| Disk full | Unrotated logs or old images | Set log options and prune unused images |
| Service restarts repeatedly | Crash loop | Check logs and RestartCount, fix the bug |
| Database reachable from internet | Published port | Remove the ports mapping |
| Update causes outage | Container recreated | Schedule a window or add a proxy-based pattern |
| Services missing after reboot | Docker service not enabled | systemctl enable docker |