09. Docker Compose
9.1 Compose Fundamentals
Section titled “9.1 Compose Fundamentals”What is Docker Compose?
Section titled “What is Docker Compose?”Docker Compose is an orchestration tool (included with Docker Desktop and modern Docker Engine installs). It allows you to spin up web servers, databases, and message queues simultaneously with a single command, automatically wiring them together on a shared network.
compose.yaml (or docker-compose.yml)
Section titled “compose.yaml (or docker-compose.yml)”The configuration file where you declare your stack. (Note: compose.yaml is the modern preferred naming convention over the older docker-compose.yml).
Core Concepts
Section titled “Core Concepts”A Compose file is broken down into three main top-level keys:
services: The actual containers you want to run (e.g.,web,db,redis).networks: Custom networks for your services to communicate on.volumes: Persistent data storage to attach to your services.
9.2 Compose Services
Section titled “9.2 Compose Services”The services block is where you define the configuration for each container.
services: web: image: nginx:alpine container_name: web-server ports: - "8080:80"Key Service Directives
Section titled “Key Service Directives”image: Specifies the pre-built image to pull and use.build: Instead of pulling an image, tells Compose to build an image from a localDockerfile(e.g.,build: ./backend).container_name: Overrides Compose’s default generated naming scheme (which is usuallyproject-service-1).command: Overrides the defaultCMDspecified in the Dockerfile.entrypoint: Overrides the defaultENTRYPOINTspecified in the Dockerfile.ports: Maps host ports to container ports (Format:HOST:CONTAINER). Maps todocker run -p.expose: Documents internal ports (does not publish them to the host).environment: Defines environment variables directly in the YAML file.env_file: Loads environment variables from an external file (e.g.,env_file: .env).volumes: Mounts named volumes or bind mounts into the container.networks: Attaches the service to specific custom networks defined in the file.depends_on: Dictates startup order. Ifwebdepends ondb, Compose will startdbfirst.restart: Defines the restart policy (always,unless-stopped,on-failure).
9.3 Compose Networking
Section titled “9.3 Compose Networking”Compose makes networking incredibly simple.
Default Network
Section titled “Default Network”By default, Compose automatically creates a single, private bridge network for your entire stack. Every service you define is automatically attached to this network.
Service Discovery & Internal Communication
Section titled “Service Discovery & Internal Communication”You do not need to use IP addresses to let your containers talk. The name of the service in the YAML file automatically becomes its DNS hostname on the default network!
- If the
webservice needs to connect to thedbservice, it literally just connects tohttp://db:5432.
Custom Networks
Section titled “Custom Networks”You can define multiple isolated networks if you want strict security (e.g., a frontend-net and a backend-net).
networks: frontend: backend:
services: web: networks: - frontend api: networks: - frontend - backend db: networks: - backend(In this example, the web container cannot reach the db container directly).
9.4 Compose Volumes
Section titled “9.4 Compose Volumes”To ensure your databases survive a stack teardown, you must define volumes at the bottom of the file.
Named Volumes
Section titled “Named Volumes”services: db: image: postgres volumes: - pgdata:/var/lib/postgresql/data
# Must declare the volume globally here!volumes: pgdata:Bind Mounts
Section titled “Bind Mounts”Bind mounts do not need to be declared globally, just inside the service:
services: web: image: node volumes: - ./src:/app/src9.5 Environment Management
Section titled “9.5 Environment Management”Hardcoding passwords into a compose.yaml file is a massive security risk.
.env File
Section titled “.env File”Compose automatically looks for a file named .env in the same directory. You can store your secrets there.
# .env fileDB_PASS=supersecretUsing Variables in Compose
Section titled “Using Variables in Compose”You inject the variables into the YAML using ${VAR_NAME} syntax:
services: db: image: postgres environment: POSTGRES_PASSWORD: ${DB_PASS}env_file
Section titled “env_file”If your container expects a massive list of environment variables, pass the whole file directly instead of listing them one by one.
services: api: env_file: .env9.6 Healthchecks
Section titled “9.6 Healthchecks”A container might be “Running” but the application inside it might be frozen or still booting up. Healthchecks solve this by actively testing the container.
Healthcheck Syntax
Section titled “Healthcheck Syntax”services: web: image: nginx healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 10s retries: 3healthy vs unhealthy
Section titled “healthy vs unhealthy”When a healthcheck is configured, docker ps will show the status as (health: starting). Once the test passes, it becomes (healthy). If the test fails 3 times (retries: 3), it becomes (unhealthy).
Dependency Conditions
Section titled “Dependency Conditions”You can combine healthchecks with depends_on to ensure the web service doesn’t start until the db is fully ready to accept connections, rather than just “running”.
services: web: depends_on: db: condition: service_healthy9.7 Compose Commands
Section titled “9.7 Compose Commands”Execute these in the same directory as your compose.yaml. (Note: docker compose has officially replaced the old Python-based docker-compose binary).
docker compose up -d: Builds (if necessary), creates, and starts all containers, networks, and volumes in the background (-ddetached).docker compose down: Stops and deletes all containers and networks. (It intentionally leaves Volumes alone to protect your data!)docker compose ps: Lists the containers specifically belonging to this Compose stack.docker compose logs -f: Tails the aggregated logs of all services in the stack simultaneously.docker compose exec <service> sh: Opens a shell inside a specific service (e.g.,docker compose exec db bash).docker compose build: Rebuilds all services that have abuild:directive.docker compose pull: Pulls the latest versions of allimage:directives from the registry.docker compose restart: Restarts the entire stack without destroying it.
9.8 Production Compose
Section titled “9.8 Production Compose”Compose is fantastic for development, but requires careful configuration for production.
Development vs Production
Section titled “Development vs Production”In dev, you use Bind Mounts for hot-reloading code. In production, you build the code into immutable images and use Named Volumes.
Multiple Compose Files
Section titled “Multiple Compose Files”You can merge Compose files to override configurations for different environments.
# Merges compose.yaml (base) with compose.prod.yaml (production overrides like ports or scaling limits)docker compose -f compose.yaml -f compose.prod.yaml up -dSecrets
Section titled “Secrets”Docker Compose supports reading secrets from files without injecting them as environment variables (which can be leaked). Use the secrets: block for high-security deployments.
Resource Limits
Section titled “Resource Limits”You can restrict how much CPU and RAM a container is allowed to consume to prevent one service from crashing the whole server.
services: web: deploy: resources: limits: cpus: '0.50' memory: 512M