Module Review: Docker Compose
[!NOTE] This module explores the core principles of Module Review: Docker Compose, deriving solutions from first principles and hardware constraints to build world-class, production-ready expertise.
1. Key Takeaways
- Declarative > Imperative: Use
docker-compose.yamlto define your stack instead of running 10 manual commands. - Service Networking: Every service is automatically discoverable by its name (e.g.,
ping db). - Config Separation: Use
.envfiles and environment variables to keep secrets out of your code. - Healthchecks: Use
depends_on: condition: service_healthyto ensure dependencies are actually ready, not just started. - Scaling: Use
--scaleto run multiple replicas, but ensure you don’t bind host ports directly to scaled services.
2. Flashcards
Test your knowledge. Click to flip.
What is the difference between `depends_on` and `depends_on: condition: service_healthy`?
Basic `depends_on` only waits for the container to START. Adding `service_healthy` waits for the HEALTHCHECK to pass (e.g., DB actually accepting connections).
Why can't you scale a service that has `ports: "80:80"`?
Port Conflict. Only one process can bind to Host Port 80. To scale, remove the host binding and use a Load Balancer.
How does `app` connect to `db` in Compose?
By using the service name `db` as the hostname. Docker's internal DNS resolves `db` to the container's IP address.
Which environment variable takes precedence: `.env` file or Shell Environment?
Shell Environment. If you run `export FOO=bar` and then `docker compose up`, `FOO` will be `bar` even if `.env` says `FOO=baz`.
What is the purpose of `volumes` in Compose?
To persist data. Named volumes (like `db_data`) survive container removal (`docker compose down`).
3. Cheat Sheet
| Command | Description |
|---|---|
docker compose up -d |
Start all services in background |
docker compose down |
Stop and remove containers & networks |
docker compose down -v |
… and remove Volumes (Data Loss!) |
docker compose logs -f |
View logs (follow mode) |
docker compose ps |
List running services |
docker compose exec app sh |
Shell into app service |
docker compose build |
Rebuild images from Dockerfiles |
| YAML Key | Description |
|---|---|
version |
Deprecated (optional). |
services |
Define containers. |
build |
Build from source. |
image |
Pull from registry. |
ports |
Host:Container mapping. |
volumes |
Host:Container storage. |
environment |
Set env vars. |
depends_on |
Startup order. |
healthcheck |
Readiness probe. |
restart |
Restart policy (always/on-failure). |
Next Steps
Now that you can orchestrate multi-container apps, it’s time to learn how to secure them.