Compose in practice
Define a multi-service app once: health checks, ordering, volumes and environment.
Docker Compose describes several containers, their networks and volumes in one YAML file, so one command starts the whole application.
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets: [db_password]
volumes:
- dbdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
retries: 10
api:
build: ./api
ports:
- "127.0.0.1:3000:3000"
environment:
DB_HOST: db
depends_on:
db:
condition: service_healthy
volumes:
dbdata:
secrets:
db_password:
file: ./db_password.txt- Compose creates a network for the project, so
apireaches the database asdb. healthcheckplusdepends_on: condition: service_healthymakesapiwait until the database really accepts connections. Plaindepends_ononly waits for the container to start.- A named volume (
dbdata) keeps data when containers are recreated.
docker compose up -d --build
docker compose ps
docker compose logs -f api
docker compose down # stop and remove containers
docker compose down -v # also delete named volumes (data is lost!)Carefuldocker compose down -v deletes your volumes, including database data. Use it only when you want a clean start.
NoteKeep configuration in environment variables or an .env file that is not committed. Use docker compose config to see the final, merged configuration.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.