Skip to main content

Running Docker Compose in Production

Run Docker Compose in production on a single host with logging, limits, secrets, backups, and safe updates, and know when to move on.

44 Terms

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.

flowchart TD U[Users] -->|HTTPS| N[nginx proxy] N -->|private network| A[api] A -->|private network| P[(postgres)] P -->|nightly dump| B[Backup storage] classDef edge fill:#F97316,color:#FFFFFF classDef app fill:#DBEAFE,color:#1E293B classDef data fill:#D1FAE5,color:#1E293B class N edge class A app class P,B data

Use this checklist to decide whether Compose fits:

  1. One host is acceptable. If the machine fails, you can restore or recreate it within your allowed downtime.
  2. Brief restarts are acceptable. Updating a container causes a short interruption.
  3. Manual scaling is enough. Traffic fits one machine, or you can resize the VM.
  4. 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.

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.txt

The !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.

Bash
# Avoid repeating -f flags
export COMPOSE_FILE=compose.yaml:compose.prod.yaml
# Inspect exactly what will run
docker compose config
How 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.

Bash
sudo systemctl enable docker
sudo reboot
docker compose ps # services return without manual action
How 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.

Bash
cd /opt/payment-api
sed -i 's/^IMAGE_TAG=.*/IMAGE_TAG=a3f8c12/' .env
docker compose pull api
docker 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.

Bash
sed -i 's/^IMAGE_TAG=.*/IMAGE_TAG=9b21d4e/' .env # previous known-good tag
docker compose up -d --no-deps --wait api
docker 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.

Bash
# Logical backup from inside the container
docker 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 database
docker compose exec -T postgres pg_restore -U api_user -d payments --clean < /backups/payments-2025-01-15.dump

Test 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, not always: always starts a container again after a daemon restart even if you stopped it on purpose for maintenance.
  • Rotate logs: the default json-file driver does not rotate, so set max-size and max-file or 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.
Tip

Export COMPOSE_FILE=compose.yaml:compose.prod.yaml in the deployment user's shell profile so nobody runs a command against the wrong file set by accident.

Remember

Compose 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 Mistake

Treating 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.

Security

Do 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

Resources

Explore More in Docker Compose and Multi-Container Applications

All 6 Topics

Frequently Asked Questions

Is Running Docker Compose in Production free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Running Docker Compose in Production topic cover?

Run Docker Compose in production on a single host with logging, limits, secrets, backups, and safe updates, and know when to move on.

Found a mistake, an outdated step or a broken link?