Skip to content

Chapter 1 of 8

Compose File Anatomy

A Docker Compose file is a YAML document that describes a multi-container application. In Compose v2, the modern format no longer requires a top-level version: field; the schema is inferred from the features you use. The top-level keys you'll encounter are services, networks, volumes, secrets, configs, and name. Inside each service definition under services:, the most-used keys are image, build, ports, environment, env_file, volumes, depends_on, healthcheck, restart, command, and networks. A service either runs a pre-built image referenced by tag or digest, or is built from a Dockerfile using a build: block.

Environment configuration in Compose has two distinct concepts that often confuse newcomers. The .env file in the same directory as your compose file is auto-loaded by Compose for variable interpolation inside the YAML itself, with values referenced as ${VAR}. The env_file: key on a service, on the other hand, populates environment variables inside the running container at runtime. To set variables inline you use environment: with a list of KEY=value pairs, and to inherit a value from the shell you write just the key with no value, e.g. environment: - HOME. You can also override values on the command line with WEB_PORT=4000 docker compose up, but only if the compose file uses \({WEB_PORT} interpolation.

Compose supports a shell-like interpolation language for variable references. A bare \){VAR} resolves to the empty string if the variable is unset. Use \({VAR:-default} to supply a fallback when the variable is unset or empty, and \){VAR:?error message} to make Compose fail loudly if the variable is missing, which is the strict mode you want for production. To include a literal dollar sign in a value, escape it as $$, because an unescaped $ will be treated as the start of an interpolation. The docker compose config command is invaluable here: it validates the file and prints the fully resolved configuration with all interpolation applied, which is the fastest way to debug why a variable isn't showing up where you expect.

All chapters
  1. 1Compose File Anatomy
  2. 2Services, Dependencies, and Health
  3. 3Volumes, Mounts, and Data Persistence
  4. 4Networking in Compose
  5. 5Building, Scaling, and Resources
  6. 6Multi-Environment Compose and Configuration
  7. 7Logs, Debugging, and Common Gotchas
  8. 8Stack-Specific Recipes and Patterns

Drill it

Reading is not remembering. These come from the Docker Compose Recipes For Local Dev deck:

Q

Compose file directive to mount a host directory into a container?

volumes: - ./local:/app

Q

Restart a container automatically unless explicitly stopped?

restart: unless-stopped

Q

Define an environment variable in Compose?

environment:<br> - KEY=value or env_file: .env

Q

Wait for another service to be 'healthy' before starting?

depends_on:<br> db:<br> condition: service_healthy