πWhat Docker Compose Solves
Real applications are never one container. A typical app has an API, a database, a cache and a front end. Starting each with a long docker run command, wiring networks and remembering environment variables is slow and error prone. Docker Compose lets you describe the whole stack in one file and start it with one command.
In 2026, Compose is built into the Docker CLI as docker compose (with a space). The old standalone docker-compose binary is legacy. The file is usually named compose.yaml, and the top level version key is obsolete, so you can leave it out.
If containers are new to you, start with the Docker course page and Docker image best practices.
πThe Example App
We will run four services:
Project layout:
shop/ compose.yaml .env api/ Dockerfile web/ DockerfileπThe Complete compose.yaml
name: shopservices: db: image: postgres:16-alpine environment: POSTGRES_DB: shop POSTGRES_USER: shop POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U shop -d shop"] interval: 5s timeout: 3s retries: 10 networks: [backend] cache: image: redis:7-alpine healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s retries: 10 networks: [backend] api: build: ./api env_file: .env environment: DATABASE_URL: postgres://shop:${POSTGRES_PASSWORD}@db:5432/shop REDIS_URL: redis://cache:6379 depends_on: db: condition: service_healthy cache: condition: service_healthy ports: - "8080:8080" networks: [backend, frontend] develop: watch: - action: sync path: ./api/src target: /app/src - action: rebuild path: ./api/package.json web: build: ./web ports: - "3000:80" depends_on: - api networks: [frontend] adminer: image: adminer ports: - "8081:8080" profiles: [debug] networks: [backend]volumes: pgdata:networks: backend: frontend:And the .env file next to it:
POSTGRES_PASSWORD=change-me-locallyNODE_ENV=developmentNever commit real secrets. Add .env to .gitignore and commit a .env.example instead.
πThe Dockerfiles
Compose builds the api and web images from these Dockerfiles. Both use multi-stage builds so the final images stay small.
# api/DockerfileFROM node:22-alpine AS depsWORKDIR /appCOPY package*.json ./RUN npm ci --omit=devFROM node:22-alpineWORKDIR /appCOPY --from=deps /app/node_modules ./node_modulesCOPY src ./srcUSER nodeEXPOSE 8080CMD ["node", "src/server.js"]# web/DockerfileFROM node:22-alpine AS buildWORKDIR /appCOPY package*.json ./RUN npm ciCOPY . .RUN npm run buildFROM nginx:1.27-alpineCOPY --from=build /app/dist /usr/share/nginx/htmlA Spring Boot API works the same way: build the jar in a Maven or Gradle stage, then copy it into a slim JRE image. The compose.yaml does not change.
πWalking Through the File
services
Each key under services is one container definition. Compose names containers using the project name, here shop, so you get shop-api-1, shop-db-1 and so on.image versus build
image pulls a ready image from a registry. build builds from a Dockerfile in the given folder. Pin image versions such as postgres:16-alpine rather than latest, so your stack does not change under you.environment and env_file
environment sets variables directly. env_file loads a whole file into the container. Values like ${POSTGRES_PASSWORD} are substituted by Compose from your shell or the .env file in the project folder.Networks and service discovery
Compose creates networks and attaches services to them. Inside a network, service names become hostnames. That is why the API connects to db:5432 and cache:6379, not localhost. Here the front end cannot reach the database directly because they share no network, a small but useful security boundary.volumes
pgdata is a named volume, so your database survives docker compose down. Use bind mounts like ./api/src:/app/src only for source code during development.ports
"8080:8080" maps host port to container port. Only expose what you need on the host. The database here has no ports entry, so it is reachable only from inside the backend network.πHealthchecks and depends_on Conditions
A plain depends_on only waits for a container to start, not to be ready. Postgres takes a few seconds to accept connections, so an API that starts immediately crashes.
The fix is a healthcheck plus a condition:
depends_on: db: condition: service_healthyNow Compose starts the API only after pg_isready succeeds. Other conditions are service_started and service_completed_successfully, useful for a one-off migration container that must finish before the API starts.
Your application should still retry connections, because databases can restart in production too.
πProfiles
Some services are only needed occasionally, like Adminer for browsing the database. Put them in a profile:
docker compose up -d # starts everything except adminerdocker compose --profile debug up -d # also starts adminerπWatch Mode for Fast Development
The develop.watch section lets Compose react to file changes:
Run it with:
docker compose watchπEveryday Commands
docker compose up -d --build # build and start in the backgrounddocker compose ps # status of all servicesdocker compose logs -f api # follow logs for one servicedocker compose exec db psql -U shop -d shopdocker compose restart apidocker compose down # stop and remove containers, keep volumesdocker compose down -v # also delete volumes (data is lost)docker compose config # print the resolved file, great for debuggingπOverrides for Different Environments
Compose automatically merges compose.override.yaml if it exists, which is handy for local only settings such as bind mounts and debug ports. For other environments, pass files explicitly:
docker compose -f compose.yaml -f compose.prod.yaml up -dπCommon Errors and Fixes
Port is already allocated
Another process or container uses that host port. Change the left side of the mapping, or stop the other process.API cannot connect to localhost:5432
Inside a container, localhost is the container itself. Use the service name, db.Connection refused at startup
The database was not ready. Add a healthcheck and condition: service_healthy, and add retries in your app.Changes to code are not showing
You are running an old image. Usedocker compose up -d --build or watch mode.Database data disappeared
You randown -v, or used an anonymous volume. Use a named volume and avoid -v unless you mean it.Variable is not set, defaulting to a blank string
Compose could not find the variable. Check the .env file is in the project folder and rundocker compose config to see the resolved values.πScaling a Service Locally
Compose can run more than one copy of a stateless service, useful for testing load balancing:
docker compose up -d --scale api=3Remove the fixed host port from the api service first, or the extra copies will clash on port 8080, and put a reverse proxy such as Nginx or Traefik in front. This is also a good moment to notice the limits of Compose: everything still runs on one machine.
πDocker Compose Best Practices
πCompose in CI Pipelines
Compose is a great way to run integration tests. A typical pipeline step starts the database and cache, runs the API test suite against them and tears everything down:
docker compose up -d db cache --waitdocker compose run --rm api npm testdocker compose down -vThe --wait flag blocks until the started services are healthy, so tests never race a database that is still booting. Read the GitHub Actions CI/CD tutorial to wire this into a real pipeline.
πCompose or Kubernetes?
Compose is perfect for local development, demos, CI test environments and small single host deployments. When you need multiple nodes, self healing, autoscaling and rolling deployments, move to Kubernetes. Read Docker vs Kubernetes and the Kubernetes roadmap.
πFAQ
Is docker-compose deprecated?
The standalone v1 docker-compose tool is retired. Usedocker compose, which is Compose v2 built into the Docker CLI.Do I still need the version field?
No. It is obsolete and ignored by current Compose.Can I use Compose in production?
For small single server apps, yes, with restart policies and care around secrets and backups. For larger systems, use Kubernetes.Where can I practise interview questions?
See the Docker interview questions.πLearn It Live
Prakalpana's Docker & Containerization course is taught live online with an optional 1-on-1 track, where you containerise real multi-service apps and move them to Kubernetes. See the Docker track and the wider DevOps course, or WhatsApp or call +91 9180377502 for a free demo.