Docker Compose basics (multi-container stack)
Topic: Containers core
Summary
Define a multi-container stack in a compose file (docker-compose.yml): services, networks, volumes. Run with docker compose up -d; manage with docker compose down and docker compose logs. Use this when running an app with a database, cache, or multiple services on one host.
Intent: How-to
Quick answer
- compose file: services with image or build, ports, volumes, environment, depends_on. networks and volumes at top level. docker compose up -d builds (if build: present) and starts all services. docker compose down stops and removes containers (and optionally volumes with -v).
- Service dependency: depends_on: - db ensures db starts before app; does not wait for db to be ready (use healthcheck and condition for that). Use same network so services resolve by service name (e.g. app connects to db:5432).
- Override: docker-compose.override.yml for local overrides; or -f file.yml. Environment: use env_file or environment; use .env file for default env vars. Do not commit secrets; use env_file that is gitignored or inject at runtime.
Prerequisites
Steps
-
Write compose file
services: app: image: myapp:1; ports: - 8080:80; environment: DB_HOST=db; depends_on: - db. db: image: postgres:16; volumes: - pgdata:/var/lib/postgresql/data; environment: POSTGRES_PASSWORD=secret. volumes: pgdata:.
-
Start stack
docker compose up -d. docker compose ps; docker compose logs -f. Services are on a default network; app can reach db at hostname db.
-
Stop and remove
docker compose down. docker compose down -v to remove named volumes (data loss). docker compose up -d --build to rebuild and start.
-
Override and env
Put secrets in .env (gitignore) or pass at runtime. Use docker-compose.override.yml for local dev (e.g. mount source, different ports).
Summary
Define services, networks, and volumes in a compose file; run with docker compose up -d. Use this to run and manage a multi-container stack on one host.
Prerequisites
Steps
Step 1: Write compose file
Define services with image or build, ports, volumes, environment, and depends_on; define shared volumes and networks.
Step 2: Start stack
Run docker compose up -d; check status and logs; use service names for inter-service communication.
Step 3: Stop and remove
Use docker compose down; use -v only when you intend to remove volumes.
Step 4: Override and env
Use .env and override files for local config; keep secrets out of the repo.
Verification
- All services start; app can reach dependencies by service name; logs and health are acceptable.
Troubleshooting
Service cannot reach another — Ensure they are on the same compose network; use service name as hostname. Build fails — Check build context and Dockerfile path in compose; run docker compose build for verbose output.