Docker · Lesson 7 of 8
Docker Compose: Your Whole Stack
One file, one command.
Typing long docker run commands for every container gets old fast. Docker Compose lets you describe the whole stack, every service, port, volume and network, in one YAML file, and start it all with a single command.
A compose.yaml for a web app, database and cache
compose.yamlyaml
services:
web:
build: .
ports:
- "8080:5000"
environment:
DATABASE_URL: postgresql://postgres:secret@db:5432/postgres
REDIS_URL: redis://cache:6379
depends_on:
- db
- cache
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
volumes:
- pgdata:/var/lib/postgresql/data
cache:
image: redis:7
volumes:
pgdata:Compose creates a network for the project automatically, so web reaches the others as db and cache.
Run the stack
terminal
docker compose up -d --build [+] Running 4/4 ✔ Network app_default Created ✔ Container app-db-1 Started ✔ Container app-cache-1 Started ✔ Container app-web-1 Started docker compose ps NAME SERVICE STATUS PORTS app-web-1 web running 0.0.0.0:8080->5000/tcp app-db-1 db running 5432/tcp app-cache-1 cache running 6379/tcp docker compose logs -f web web-1 | * Running on http://0.0.0.0:5000 docker compose down ✔ Container app-web-1 Removed ✔ Network app_default Removed
Everyday Compose commands
| Command | What it does |
|---|---|
| docker compose up -d | start everything in the background |
| docker compose up -d --build | rebuild images, then start |
| docker compose logs -f SERVICE | follow one service's logs |
| docker compose exec SERVICE sh | open a shell in a running service |
| docker compose down | stop and remove containers and the network |
| docker compose down -v | also delete the volumes (careful: deletes data) |
Try it yourself
✍️ Exercise: Add an admin tool
Add an adminer service (image adminer) to the compose file, published on port 8081, so you can browse the database from your browser.
Show hint
a new service with image and ports
Show solution
compose.yamlyaml
adminer:
image: adminer
ports:
- "8081:8080"
depends_on:
- dbSummary
Key takeaways
- compose.yaml describes every service in one place
- docker compose up -d starts the whole stack
- Services reach each other by service name
Next up: Recap & Next Steps — where to go from here