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.yamlfor an API, PostgreSQL, and Redis. - Understand how services, the project network, and volumes fit together.
- Keep passwords out of the file using
.envinterpolation and secrets. - Run, inspect, debug, and tear down the stack with the Compose CLI.
- Tell
execandrunapart, and know whatdown -vreally 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.
Four ideas explain most of how Compose behaves:
- 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. - 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. - Named volumes hold state. Data written to a named volume survives
docker compose down, while data in the container filesystem does not. - 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.
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 volumeCreate a .env file in the same folder. Compose reads it automatically for ${...} interpolation, and you must add it to .gitignore.
echo "DB_PASSWORD=local-dev-password" > .envecho ".env" >> .gitignoreHow to Start, Inspect, and Stop the Stack
# Validate and print the fully resolved file (variables substituted)docker compose config # Start everything in the background, rebuilding the API image firstdocker compose up -d --build # Status and health of every servicedocker 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 onedocker compose logs --tail=50docker compose logs -f payment-api # Running processes inside each containerdocker 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 volumesdocker compose downHow to Pass Environment Variables and Secrets Safely
Compose has three mechanisms that people often mix up:
.envfile: used by Compose itself for${VAR}interpolation insidecompose.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 indocker inspectas an environment variable.
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 .gitignoreUse ${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
# exec: run inside an already running containerdocker compose exec postgres psql -U api_user -d payments # run: start a new throwaway container from the service definitiondocker compose run --rm payment-api npm run migraterun 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
docker compose up -d --scale payment-api=3Scaling 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, notpostgres:latest, so a pull cannot silently change your database major version. - Never commit secrets: keep
.envand secret files out of git, and commit an.env.examplewith fake values. - Treat
down -vas destructive:docker compose downkeeps named volumes, whiledocker compose down -vdeletes them and all their data. - Add health checks and wait for them: plain
depends_ononly waits for the container to start, not for the app inside to be ready. - Do not set
container_nameby default: it blocks scaling and can collide with other projects. - Use Compose v2: the command is
docker composewith a space. The old hyphenateddocker-composeis Compose v1, which no longer receives updates.
TipRun
docker compose configbefore 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 downkeeps your volumes.docker compose down -vdeletes them permanently. This is the most common cause of accidental data loss in Compose projects.
Common MistakeUsing
depends_on: [postgres]and assuming the API will wait for the database to accept connections. Add ahealthcheckto PostgreSQL and usecondition: service_healthy.
SecurityNever hardcode passwords in
compose.yaml. Use.envfor local work, Composesecretsor 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 |