Skip to main content

Defining Multi-Container Apps with Docker Compose

Learn the Docker Compose file structure: services, networks, volumes, env files, and the CLI commands to run multi-container apps.

44 Terms

Overview and What You Will Learn

Docker Compose lets you describe a multi-container application in one YAML file and run all of it with one command. Instead of installing PostgreSQL and Redis on your laptop and remembering a pile of docker run flags, you declare the services, networks, and volumes once, and docker compose up creates them in the right order.

In this lab you will:

  • Write a compose.yaml for an API, PostgreSQL, and Redis.
  • Understand how services, the project network, and volumes fit together.
  • Keep passwords out of the file using .env interpolation and secrets.
  • Run, inspect, debug, and tear down the stack with the Compose CLI.
  • Tell exec and run apart, and know what down -v really deletes.

Why This Matters in Production

A Compose file is the shared definition of "what runs together" for development, CI, and preview environments. When a new engineer joins a team that runs an API, a database, and a cache, the whole stack should start in minutes from the repository, not from a wiki page that went stale months ago. Teams at companies such as Atlassian, Grab, and Shopify rely on this kind of repeatable local environment so that bugs reproduce the same way on every machine.

The same file also documents your architecture: which services exist, which ports they expose, and which ones depend on each other. That makes reviews and onboarding faster, and it is the natural starting point if you later move the workload to Kubernetes.

Core Principles

A Compose file has three top-level building blocks, and Compose turns them into one isolated project.

flowchart TD F[compose.yaml] -->|defines| S[Services] F -->|defines| N[Networks] F -->|defines| V[(Volumes)] S -->|become| C([Containers]) N -->|connect| C V -->|persist data for| C classDef file fill:#326CE5,color:#FFFFFF classDef part fill:#DBEAFE,color:#1E293B classDef run fill:#10B981,color:#FFFFFF class F file class S,N,V part class C run

Four ideas explain most of how Compose behaves:

  1. A service is a definition, not a container. Each key under services: describes how to run one component. Compose creates one or more containers from it.
  2. Every project gets a private network. All services join it automatically, and each service name becomes a DNS hostname, so the API reaches the database at postgres.
  3. Named volumes hold state. Data written to a named volume survives docker compose down, while data in the container filesystem does not.
  4. The project name prefixes everything. Containers, networks, and volumes are named <project>-<service>-<n>, which keeps two projects on one host from colliding.

Detailed Step-by-Step Practical Lab

How to Write a Compose File for an API, PostgreSQL, and Redis

Create compose.yaml next to your Dockerfile. The top-level version: key is obsolete in current Compose, so leave it out.

YAML
name: payment-platform # project name, prefixes all resource names
services:
payment-api:
build:
context: .
dockerfile: Dockerfile
image: payment-api:dev
ports:
- "8080:8080" # host:container
environment:
NODE_ENV: development
DB_HOST: postgres # the service name is the hostname
DB_NAME: payments
DB_USER: api_user
DB_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
REDIS_HOST: redis
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
restart: unless-stopped
postgres:
image: postgres:16-alpine
environment:
POSTGRES_DB: payments
POSTGRES_USER: api_user
POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U api_user -d payments"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
volumes:
postgres-data: # Docker creates and manages this volume

Create a .env file in the same folder. Compose reads it automatically for ${...} interpolation, and you must add it to .gitignore.

Bash
echo "DB_PASSWORD=local-dev-password" > .env
echo ".env" >> .gitignore
How to Start, Inspect, and Stop the Stack
Bash
# Validate and print the fully resolved file (variables substituted)
docker compose config
# Start everything in the background, rebuilding the API image first
docker compose up -d --build
# Status and health of every service
docker compose ps
# NAME STATUS
# payment-platform-postgres-1 Up 20 seconds (healthy)
# payment-platform-redis-1 Up 20 seconds (healthy)
# payment-platform-payment-api-1 Up 12 seconds
# Logs: all services, or follow one
docker compose logs --tail=50
docker compose logs -f payment-api
# Running processes inside each container
docker compose top
# Live CPU and memory (this is docker stats, not compose top)
docker stats --no-stream
# Stop and remove containers and the network, keep volumes
docker compose down
How to Pass Environment Variables and Secrets Safely

Compose has three mechanisms that people often mix up:

  • .env file: used by Compose itself for ${VAR} interpolation inside compose.yaml.
  • env_file: key: loads every variable in a file into the container environment.
  • secrets: key: mounts a value as a file at /run/secrets/<name> so it never appears in docker inspect as an environment variable.
YAML
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txt # keep this path in .gitignore

Use ${VAR:-default} for optional values and ${VAR:?message} to fail early with a clear error when a required variable is missing.

How to Run One-Off Commands: exec vs run
Bash
# exec: run inside an already running container
docker compose exec postgres psql -U api_user -d payments
# run: start a new throwaway container from the service definition
docker compose run --rm payment-api npm run migrate

run creates a separate container with the same configuration, which makes it the right choice for migrations and scripts. Add --no-deps if you do not want it to start dependencies.

How to Scale a Service
Bash
docker compose up -d --scale payment-api=3

Scaling only works if the service does not set container_name and does not publish one fixed host port, because two containers cannot share either.

Production Best Practices & Common Pitfalls

  • Pin image tags: use postgres:16-alpine, not postgres:latest, so a pull cannot silently change your database major version.
  • Never commit secrets: keep .env and secret files out of git, and commit an .env.example with fake values.
  • Treat down -v as destructive: docker compose down keeps named volumes, while docker compose down -v deletes them and all their data.
  • Add health checks and wait for them: plain depends_on only waits for the container to start, not for the app inside to be ready.
  • Do not set container_name by default: it blocks scaling and can collide with other projects.
  • Use Compose v2: the command is docker compose with a space. The old hyphenated docker-compose is Compose v1, which no longer receives updates.
Tip

Run docker compose config before every first start on a new machine. It shows exactly what Compose will run, including every interpolated variable, and catches indentation and typo errors early.

Remember

docker compose down keeps your volumes. docker compose down -v deletes them permanently. This is the most common cause of accidental data loss in Compose projects.

Common Mistake

Using depends_on: [postgres] and assuming the API will wait for the database to accept connections. Add a healthcheck to PostgreSQL and use condition: service_healthy.

Security

Never hardcode passwords in compose.yaml. Use .env for local work, Compose secrets or a secret manager for anything shared, and rotate any credential that was ever committed.

Quick Reference & Troubleshooting Commands

Command Description
docker compose up -d --build Build images and start all services in the background
docker compose ps Show service state and health
docker compose logs -f <service> Follow logs for one service
docker compose exec <service> sh Open a shell in a running container
docker compose run --rm <service> <cmd> Run a one-off command in a new container
docker compose config Print the resolved configuration
docker compose down Remove containers and network, keep volumes
docker compose down -v Also delete named volumes and their data
Problem Likely cause Fix
required variable DB_PASSWORD is missing No .env file or variable unset Create .env with the variable
API cannot reach postgres Wrong hostname or different network Use the service name and check docker compose config
Port already allocated Another process uses the host port Change the left side of the port mapping
Scaling fails container_name or fixed host port set Remove them or use a port range
Data missing after restart Wrote to container filesystem Mount a named volume at the data path

Resources

Explore More in Docker Compose and Multi-Container Applications

All 6 Topics

Frequently Asked Questions

Is Defining Multi-Container Apps with Docker Compose 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 Defining Multi-Container Apps with Docker Compose topic cover?

Learn the Docker Compose file structure: services, networks, volumes, env files, and the CLI commands to run multi-container apps.

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