The first time I worked on a real app with a database, a queue, and a worker, my docker run commands got so long I started saving them as shell scripts. Three weeks later I had four scripts, all slightly different, all wrong in their own special way, and a junior dev who couldn't get the stack running without messaging me at 11pm. Docker Compose exists for exactly that reason. It takes the imperative horror of docker run -d --name api -p 3000:3000 --link db:db --env-file .env -v $(pwd)/logs:/logs myimage:latest and turns it into a YAML file you can read, version, and review.
What I want to convince you of in this article is that Docker Compose isn't just a dev tool. It's a contract between your laptop, your CI pipeline, and-sometimes-your production environment. Used correctly, the same compose.yaml boots the stack on a new hire's Mac, in a GitHub Actions runner, and on a single-box VPS. Used badly, it's another pile of YAML nobody understands. We're going to do it correctly.
What Docker Compose Actually Is
Docker Compose is a declarative description of a multi-container application. You write a compose.yaml (or docker-compose.yml if you've been doing this for a while), run docker compose up, and the tool figures out which networks to create, which volumes to mount, which images to build, and in what order to start things.
The mental shift from raw docker run is the same one as going from shell scripts to Terraform: you stop describing what to do and start describing what the world should look like. Compose then reconciles. If you change a port mapping, Compose recreates only the affected containers. If you remove a service, Compose removes the container. This is the difference between "imperative ops with shell scripts" and "declarative ops with a config file."
A quick comparison of where Compose sits:
| Tool | What it describes | Production-ready? | Sweet spot |
|---|---|---|---|
| Docker run + bash | One container at a time | No | Quick experiments |
| Docker Compose | A small graph of containers | For simple stacks | Local dev, CI, small prod |
| Docker Swarm | A graph across N hosts | Yes (underused) | Small clusters, edge |
| Kubernetes | Anything, anywhere | Yes | Anything serious |
| Podman Compose | Same as Compose but rootless | Mostly | Rootless local dev |
I'll be blunt: if you're running production on Docker Compose in 2024+, you're either (a) running a small enough stack that it's fine, (b) running on a single host because the cost of K8s isn't worth it, or (c) in denial. All three are real scenarios. We'll come back to (a) and (b) in the production section.
Prerequisites
You need Docker. Specifically, you want Docker Engine 24+ with the Compose v2 plugin (docker compose, not docker-compose). On macOS and Windows, Docker Desktop ships with Compose v2 built in. On Linux, install docker-ce and docker-compose-plugin from Docker's official repo. The legacy Python docker-compose binary is end-of-life and you should not start a new project with it.
Check your version:
BashCopy docker compose version
Docker Compose version v2.27.0
If docker compose says "command not found" but docker-compose (with a hyphen) works, you're on the old Python client. Upgrade.
Beyond that, you need to be comfortable with the basics of Dockerfiles, images, and containers. If you can write a Dockerfile that builds a working image, you're ready.
Project Layout
The layout I've converged on after doing this on enough projects:
CodeCopy
plaintext
myapp/
compose.yaml # the canonical file, committed to git
compose.override.yaml # dev-only overrides, gitignored or committed depending on team
compose.prod.yaml # production overrides
.env # local env, gitignored, never commit secrets
.env.example # template, committed
app/
Dockerfile
...
worker/
Dockerfile
...
nginx/
nginx.conf
markdown
The naming matters. compose.yaml is the new default filename recognized by Docker Compose v2 (no need to type -f compose.yaml). Override files like compose.override.yaml are loaded automatically by docker compose up. Production overrides you load explicitly with docker compose -f compose.yaml -f compose.prod.yaml up.
A note on .env: Compose reads .env automatically from the directory you run the command in, and uses it for variable interpolation in the compose file. It is not the same as env_file: inside a service definition-.env is for your compose file's variables, env_file: is for the container's environment. People mix these up constantly.
Anatomy of a Compose File
A modern Compose file is just YAML with a few top-level keys. The spec has evolved a lot; the current shape looks like:
name: myapp # project name, defaults to directory name services: # the containers you want running api: image: myapp-api:latest build: context: ./app dockerfile: Dockerfile args: NODE_ENV: production ports: - "3000:3000" environment: DATABASE_URL: postgres://app:app@db:5432/app REDIS_URL: redis://redis:6379 depends_on: db: condition: service_healthy redis: condition: service_started healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/health"] interval: 10s timeout: 3s retries: 3 start_period: 10s restart: unless-stopped deploy: resources: limits: cpus: "1.0" memory: 512M reservations: cpus: "0.25" memory: 128M worker: image: myapp-api:latest # same image, different command command: ["python", "-m", "app.worker"] environment: DATABASE_URL: postgres://app:app@db:5432/app depends_on: db: condition: service_healthy redis: condition: service_started restart: unless-stopped db: image: postgres:16-alpine environment: POSTGRES_USER: app POSTGRES_PASSWORD: app POSTGRES_DB: app volumes: - db-data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U app"] interval: 5s timeout: 3s retries: 5 restart: unless-stopped redis: image: redis:7-alpine command: ["redis-server", "--save", "60", "1", "--loglevel", "warning"] volumes: - redis-data:/data restart: unless-stopped proxy: image: nginx:1.27-alpine ports: - "80:80" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro depends_on: - api restart: unless-stopped volumes: # named volumes, lifecycle managed by compose db-data: redis-data: networks: # custom networks (default is fine for most) default: driver: bridge configs: # non-sensitive configuration blobs nginx_config: file: ./nginx/nginx.conf secrets: # sensitive blobs, mounted at /run/secrets/<name> db_password: file: ./secrets/db_password.txt Five things in that file deserve explanation.
First, name: at the top sets the project name. Without it, Compose uses the directory name, which leads to surprises when two engineers have the repo checked out in differently-named folders. Set it explicitly.
Second, depends_on with a condition is the only reliable way to control startup order. The plain list form (depends_on: [db, redis]) just controls start order, not readiness. Your app will still race the database unless you add the service_healthy condition and a healthcheck on db.
Third, deploy.resources works in Compose v2 (it used to be Swarm-only). Use it. Without limits, a runaway container can OOM the host and bring down the whole stack.
Fourth, secrets and configs are distinct from environment. Secrets are mounted as files at /run/secrets/<name>, never exposed via docker inspect, and the file contents aren't logged. If you have a real secret, use this-not environment:.
Fifth, restart: unless-stopped is the right default for almost everything. always will restart containers even after you explicitly stopped them with docker compose stop, which is annoying. on-failure is for things that should stay down if they exit cleanly.
Environment Management:.env, Interpolation, and Overrides
Compose has two layers of environment handling that look similar but do very different things. Get them straight or you'll waste a day.
Variable interpolation. Any ${VAR} in your compose.yaml is resolved at parse time, from the shell environment or from a .env file in the same directory. This is for things like image tags, port numbers, and service names.
YAMLCopy services:
api:
image: myapp-api:${TAG:-latest}
ports:
- "${API_PORT:-3000}:3000"
BashCopy
conf
.env
TAG=v1.2.3
API_PORT=8080
yaml
Run docker compose up and Compose substitutes v1.2.3 for ${TAG} and 8080 for ${API_PORT}. The :-latest syntax provides a default if the variable is unset.
Container environment. The environment: key inside a service sets environment variables inside the container at runtime. This is for things your app reads via os.environ, like DATABASE_URL. These are not interpolated-they're literal values (which can themselves reference interpolation variables, if you want).
services: api: environment: DATABASE_URL: postgres://${DB_USER}:${DB_PASS}@db:5432/${DB_NAME} Here ${DB_USER} is resolved from .env, then the resulting string is set as DATABASE_URL inside the container.
Multiple env files. If you want to share env across services, use env_file::
YAMLCopy services:
api:
env_file:
- .env.common
- .env.api worker: env_file:
- .env.common
- .env.worker
These are loaded into the container. They don't affect compose-file interpolation.
Override files. The pattern that makes Compose actually scale across environments is layered overrides. Your compose.yaml is the canonical spec. Override files modify it for specific contexts.
YAMLCopy
yaml
compose.override.yaml - loaded automatically by docker compose up
services:
api:
build:
target: dev # use the dev stage of the multi-stage Dockerfile
volumes:
- ./app:/app # live code mount
- /app/node_modules # anonymous volume, prevent host overwrite command: ["npm", "run", "dev"] environment: NODE_ENV: development DEBUG: "*"
plaintext
For production, you load overrides explicitly:
BashCopy
shell
docker compose -f compose.yaml -f compose.prod.yaml up -d
plaintext
YAMLCopy
yaml
compose.prod.yaml
services:
api:
build:
target: prod
restart: always
deploy:
replicas: 3
resources:
limits:
cpus: "2.0"
memory: 1G
ports: !reset [] # don't publish ports directly; the proxy handles it
proxy:
ports:
- "80:80"
- "443:443"
markdown
The !reset tag (newer Compose) tells Compose to clear the value from the base file rather than merge. Without it, the API's port 3000:3000 would still be published in prod, which you don't want.
Build vs Image, Multi-Stage Dockerfiles
Most real-world Compose files mix image: (pre-built, from a registry) and build: (built locally from a Dockerfile) services. The pattern: use build: for services whose source you control, image: for third-party things like Postgres or Redis.
When you use build:, write a proper multi-stage Dockerfile. Here's a Node.js example that has dev and prod stages:
DockerfileCopy
docker
syntax=docker/dockerfile:1.7
FROM node:20-alpine AS base
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
--- dev stage: includes dev deps, source mounted at runtime ---
FROM base AS dev
RUN npm ci
COPY . .
CMD ["npm", "run", "dev"]
--- prod stage: minimal, no source mount, no dev deps ---
FROM base AS prod
COPY --chown=node:node . .
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "server.js"]
plaintext
The compose side:
YAMLCopy
yaml
services:
api:
build:
context: ./app
target: ${TARGET:-dev} # dev by default, prod in compose.prod.yaml
image: myapp-api:local # tag so up reuses the build until source changes
markdown
What you get: docker compose up in dev runs the dev stage with your source mounted. docker compose -f compose.yaml -f compose.prod.yaml build builds the slim prod stage. One Dockerfile, two images, one source of truth.
The image: field on a service that also has build: gives the built image a name. Without it, Compose names the image <project>_<service> and you can't easily push it. Always tag built images if you'll ever push them to a registry.
Networking: Bridge, DNS, andhost.docker.internal
Compose creates a default bridge network for your project and adds every service to it. Inside that network, services can reach each other by service name. The api service can connect to postgres://db:5432 because Compose registers db as a DNS name resolving to the db container's IP. This is the single most useful Compose feature and it's almost free.
A few gotchas:
localhost from inside a container doesn't mean your laptop. It means the container. New devs hit this constantly. If you need to reach a service running on your laptop from inside a container, use host.docker.internal (on Docker Desktop, and on Linux with extra_hosts: ["host.docker.internal:host-gateway"]).
Custom networks. The default network is fine for most apps. Define custom networks when you want isolation-say, putting admin tools on a separate network from public-facing services.
YAMLCopy
yaml
networks:
frontend:
backend:
services:
api:
networks: [backend, frontend]
proxy:
networks: [frontend]
db:
networks: [backend]
markdown
Now the proxy can't reach db directly. Useful for defense in depth.
Exposing ports. "3000:3000" publishes port 3000 on the host. "127.0.0.1:3000:3000" binds only to localhost, which is what you want for dev databases. If you write "3000:3000" on a cloud VM, you've just published your dev Postgres to the internet. Don't do that.
Volumes and Persistence
Two kinds of volumes, and they behave very differently.
Named volumes are managed by Docker. They survive container recreation, are stored in Docker's data directory, and work cross-platform without surprises.
YAMLCopy
yaml
volumes:
db-data:
services:
db:
volumes:
- db-data:/var/lib/postgresql/data
markdown
Bind mounts map a host directory to a container path. They're for live code reloading in dev. They're also where things get painful.
YAMLCopy
yaml
services:
api:
volumes:
- ./app:/app
plaintext
On Linux, bind mounts are fast and transparent. On macOS, they're slow-like, "your test suite goes from 8 seconds to 2 minutes" slow-because Docker Desktop runs in a VM and file operations cross the VM boundary. Use :cached (macOS) or :delegated to mitigate, or use the newer VirtioFS backend in Docker Desktop 4.30+, which is dramatically faster.
The other bind-mount footgun: mounting a host directory over a container directory that already has files. If your image has /app/node_modules populated, and you bind-mount ./app:/app, the host's ./app/node_modules (which is probably empty) shadows the container's. The fix:
YAMLCopy
yaml
volumes:
- ./app:/app
- /app/node_modules # anonymous volume, prevents the bind mount from shadowing this path
markdown
This anonymous volume is container-managed and survives across container recreations. It's the trick that makes Node dev in Docker actually usable.
Backing up named volumes. A pattern I've used in production for years:
BashCopy
shell
docker run --rm -v myapp_db-data:/data -v $(pwd):/backup alpine \
tar czf /backup/db-$(date +%F).tar.gz -C /data .
markdown
Restore with the inverse. Don't skip this step if you're running a real database in Compose.
Healthchecks, depends_on, and Resource Limits
The combination that turns a flaky Compose stack into a reliable one:
- Define a
healthcheckon every service that has one. - Use
depends_onwithcondition: service_healthyfor startup ordering. - Set
deploy.resourceslimits so one container can't OOM the host.
The first two together prevent the classic "api starts before db is ready, fails, restarts, eventually catches" dance that adds 30 seconds to every cold start. With a healthcheck on db and condition: service_healthy on api, Compose waits for db to actually be ready before starting api. You'd be amazed how much this improves the dev loop.
Resource limits deserve more attention than they get. Without them, a misbehaving worker can consume all the host's memory and the kernel OOM-killer will start killing random containers-including your database. Set limits generously enough that normal traffic fits, tightly enough that a runaway is contained.
The deploy key was originally Swarm-only. In Compose v2, it's honored (mostly). replicas is honored with docker compose up --scale. resources.limits is honored. placement.constraints and update_config are Swarm-only.
Profiles and Compose Watch
Profiles let you define services that only start when explicitly requested. Useful for one-off tasks, admin tools, or different dev contexts.
YAMLCopy
yaml
services:
api: { ... }
db: { ... }
mailhog:
profiles: [debug]
image: mailhog/mailhog
ports: ["1025:1025", "8025:8025"]
seed:
profiles: [tools]
build: ./seed
depends_on: [db]
plaintext
docker compose up starts only the unprofiled services. docker compose --profile debug up adds MailHog. docker compose --profile tools run seed runs the seed script once.
Compose Watch (v2.22+) is the dev feature that finally makes Compose competitive with tooling like Tilt or Skaffold. Define what to do when files change:
YAMLCopy
yaml
services:
api:
build: ./app
develop:
watch:
- action: sync path: ./app/src target: /app/src
- action: rebuild path: ./app/package.json
- action: sync+restart path: ./app/config.yaml target: /app/config.yaml
markdown
Run docker compose watch and Compose watches the listed paths. sync copies the file into the running container (fast, for hot-reloadable code). rebuild triggers a full image rebuild (for dependency changes). sync+restart copies and restarts the container (for config that needs the process to reload). For a Node or Python dev loop, this means you save a file and see the change in seconds, without rebuilding the image.
Production Considerations: When (and When Not) to Use Compose in Prod
I'll be opinionated. Docker Compose in production is fine if:
- You have one host, or a small fixed number of hosts, each running an independent Compose stack.
- Your services don't need autoscaling, advanced scheduling, or rolling updates across hosts.
- Your team is small and the operational complexity of K8s isn't worth it.
It's a bad choice if:
- You need to scale horizontally based on load.
- You need cross-host scheduling, bin-packing, or rolling deploys with zero downtime.
- You have compliance requirements that demand fine-grained network policies and admission control.
For the "fine" case, the production pattern is:
- Use
docker compose -f compose.yaml -f compose.prod.yaml up -dto start. - Set
restart: always(notunless-stopped) so services come back after a host reboot. - Put a real reverse proxy (Caddy, Traefik, Nginx) in front for TLS termination and rate limiting.
- Use
deploy.resourcesto prevent runaway containers from taking down the host. - Log to a file or to a log aggregator-don't rely on
docker logsfor long-term retention. - Set up a cron job to
docker compose pull && docker compose up -dfor image updates, or use Watchtower if you're feeling lazy (don't use Watchtower for anything customer-facing). - Back up named volumes regularly. Test restores.
For monitoring, the cheapest pattern that works: run cAdvisor and node_exporter as Compose services, scrape them with a Prometheus that's also in the Compose stack, and alert via Alertmanager. Or just ship logs to Loki and metrics to Grafana Cloud's free tier. Don't build a homegrown monitoring solution.
Common Mistakes
Using latest as the image tag. image: postgres:latest means you'll get a different Postgres version next month. Pin everything: postgres:16-alpine. Same for your own images: never deploy :latest to production, deploy :v1.2.3 or a git SHA.
Forgetting to set name: at the top of the compose file. Then two engineers in different directories run docker compose up and get different project names, which means different network names, which means they can't talk to each other if they try to share a network. Set name:.
Putting ports: on everything in production. In dev, sure. In prod, only the proxy should publish ports. Backend services should be reachable only through the proxy.
Bind-mounting source code in production. I've seen this. The image's code was at /app, but the operator mounted /home/me/app:/app "to make updates easier." Now the running container has whatever was on the host, including the .env.local file the dev forgot to remove. Build the image, run the image.
Not using healthchecks. Without them, depends_on is just suggestion. Your API will start before Postgres accepts connections and fail repeatedly.
Storing secrets in environment:. docker inspect shows environment variables in plain text. Anyone with access to the Docker socket can read them. Use the secrets: key and mount them as files.
Ignoring docker compose down -v. When you're debugging a weird state, sometimes the volume has stale data. docker compose down leaves volumes intact; docker compose down -v removes them. Use -v deliberately, not accidentally.
Troubleshooting
"Cannot start service api: network ... not found." You ran docker compose down somewhere else and it removed a network another project was using, or you have a stale reference. docker compose down && docker compose up -d rebuilds networks. If it persists, docker network prune (carefully).
Port conflict. Something else on the host is using the port. On macOS, often it's a previous Compose stack you forgot to take down. docker ps to find it, docker compose down from the right directory. On Linux, ss -tlnp | grep :5432 to find the culprit.
Mac bind mounts are absurdly slow. Docker Desktop → Settings → "Choose file sharing implementation for your containers" → VirtioFS. Restart Docker Desktop. Test again. Should be 5-10x faster.
Container keeps restarting. docker compose logs api. If the logs show OOMKilled, you need to raise the memory limit or fix the memory leak. If it's Exit code 137, same thing. If it's a crash on startup, your healthcheck might be too aggressive-give it a longer start_period.
depends_on doesn't wait. You're using the old list form, not the conditional form. Use:
YAMLCopy
yaml
depends_on:
db:
condition: service_healthy
not just depends_on: [db].
Stuck volumes. docker volume ls, find the one prefixed with your project name, docker volume rm <name>. If it says "in use," find the container with docker ps -a --filter volume=<name> and remove the container first.
Database "loses" data after docker compose up. You probably recreated the volume. Did you run down -v? Did you change the volume name in the compose file? Check docker volume ls for what's actually there.
Cost Considerations and Alternatives
Docker Compose itself is free. The cost question is about what you run it on. A single $20/month VPS can host a small production stack with a proxy, an API, a Postgres, and a Redis. That's a quarter of the cost of even the smallest managed Kubernetes cluster. For side projects, internal tools, and small B2B SaaS, this is the right answer.
For local dev, Docker Desktop is free for personal use and small orgs. For larger orgs, it's paid-around $9-$24/user/month. Alternatives:
| Tool | Cost | Notes |
|---|---|---|
| Docker Desktop | Free (personal/small), paid (large orgs) | Best UX, slow bind mounts on Mac |
| Colima | Free | Lightweight Docker Desktop alternative for Mac/Linux |
| OrbStack | Free for personal, paid for commercial | Fast, native Mac, very fast bind mounts |
| Podman + Podman Compose | Free | Rootless, slightly different behavior |
| Rancher Desktop | Free | Free for commercial, includes k3s |
For alternatives to Compose itself:
| Tool | Sweet spot | Why choose over Compose |
|---|---|---|
| Tilt | Polyglot dev with many services | Better dev loop, snapshotting |
| Skaffold | Kubernetes-native dev | You're deploying to k8s anyway |
| Devcontainer | Editor-integrated | VS Code / Cursor integration |
| Kind/K3d | Local Kubernetes | You need actual K8s behavior |
Real-World Use Cases
I've seen Compose used well in:
- SaaS side projects: a single-host stack with proxy, app, Postgres, Redis. $20/month, runs for years.
- CI environments: GitHub Actions service containers use Compose under the hood. Your
.github/workflows/test.ymlwithservices:is basically Compose. - Internal tooling: dashboards, status pages, admin tools that don't deserve their own cluster.
- Local dev stacks: the obvious one. Every modern repo should have a
compose.yamlthat brings the whole stack up with one command. - Edge deployments: industrial IoT gateways, retail kiosks. Constrained environments where K8s is overkill.
I've seen Compose used badly in:
- Multi-host production setups glued together with SSH scripts. Just use K8s at that point.
- Customer-facing apps that grew past one host. You can't really scale Compose past one host without Swarm, and Swarm is a dead-end.
- CI for monorepos with 30 services. Compose works, but you're paying for cold-start time on every job. Tilt or Nx + Compose is better.
Conclusion
Docker Compose is the unsung workhorse of modern development. It's not exciting. It doesn't have a CNCF sig. It just runs your stack, locally and in CI, and gets out of the way. The mistake is to treat it as "just a dev tool" or "training wheels for Kubernetes." It's a real piece of infrastructure with a real spec, and using it well is a craft.
The pattern that has served me best: treat your compose.yaml like production code. Review it in PRs. Pin image tags. Document override files. Back up volumes. Set healthchecks and resource limits. The discipline transfers when you eventually do move to Kubernetes, because the questions are the same-what depends on what, what's the startup order, what's the healthcheck, what happens when something dies.
Originally published on Mango Developer.
