Skip to content

09. 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.

The configuration file where you declare your stack. (Note: compose.yaml is the modern preferred naming convention over the older docker-compose.yml).

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.

The services block is where you define the configuration for each container.

services:
web:
image: nginx:alpine
container_name: web-server
ports:
- "8080:80"
  • image: Specifies the pre-built image to pull and use.
  • build: Instead of pulling an image, tells Compose to build an image from a local Dockerfile (e.g., build: ./backend).
  • container_name: Overrides Compose’s default generated naming scheme (which is usually project-service-1).
  • command: Overrides the default CMD specified in the Dockerfile.
  • entrypoint: Overrides the default ENTRYPOINT specified in the Dockerfile.
  • ports: Maps host ports to container ports (Format: HOST:CONTAINER). Maps to docker 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. If web depends on db, Compose will start db first.
  • restart: Defines the restart policy (always, unless-stopped, on-failure).

Compose makes networking incredibly simple.

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 web service needs to connect to the db service, it literally just connects to http://db:5432.

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).

To ensure your databases survive a stack teardown, you must define volumes at the bottom of the file.

services:
db:
image: postgres
volumes:
- pgdata:/var/lib/postgresql/data
# Must declare the volume globally here!
volumes:
pgdata:

Bind mounts do not need to be declared globally, just inside the service:

services:
web:
image: node
volumes:
- ./src:/app/src

Hardcoding passwords into a compose.yaml file is a massive security risk.

Compose automatically looks for a file named .env in the same directory. You can store your secrets there.

# .env file
DB_PASS=supersecret

You inject the variables into the YAML using ${VAR_NAME} syntax:

services:
db:
image: postgres
environment:
POSTGRES_PASSWORD: ${DB_PASS}

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: .env

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.

services:
web:
image: nginx
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3

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).

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_healthy

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 (-d detached).
  • 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 a build: directive.
  • docker compose pull: Pulls the latest versions of all image: directives from the registry.
  • docker compose restart: Restarts the entire stack without destroying it.

Compose is fantastic for development, but requires careful configuration for production.

In dev, you use Bind Mounts for hot-reloading code. In production, you build the code into immutable images and use Named Volumes.

You can merge Compose files to override configurations for different environments.

Terminal window
# 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 -d

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.

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