← Full reference

docker compose (file)

The compose.yaml format — services, images, ports, variables, volumes, networks, depends_on and healthcheck

A Compose file (compose.yaml or docker-compose.yml) describes several containers that run together: which image to use, which ports to open, which variables and volumes to attach, in what order to start. docker compose up reads the file and brings up everything it describes.

Docker is not installed in the sandbox. Here you can write and check the file itself: yamlschema compose file validates it against the Compose Specification schema and prints the errors.

Syntax

services:
  service_name:
    image: image:tag
    key: value
volumes:
  volume_name:
networks:
  network_name:

By default all services in the file join a shared network, and the service name serves as a DNS name: service app reaches service db at the address db. The version: key at the top of the file is obsolete and ignored.

Top level

KeyWhat it defines
servicescontainers — the main part of the file
volumesnamed volumes (data survives container re-creation)
networksnetworks; without them a single default network is created
secrets / configsfiles mounted into containers (/run/secrets/name)
nameproject name (prefix for containers, volumes, networks)

Service keys

Image and startup

KeyWhat it defines
imagethe image, e.g. postgres:16
buildbuild the image: build: . or context, dockerfile, args, target
commandoverride the image's command (CMD); as a string or a list
entrypointoverride the image's ENTRYPOINT
container_namea fixed container name (then the service can't be scaled)
user, working_dirthe process's user and working directory
restartno (default), always, on-failure, unless-stopped
profilesthe service starts only if the profile is enabled: --profile name
initrun a tiny init process that reaps zombies and forwards signals

Network and ports

KeyWhat it defines
portspublish to the host: "8080:80", "127.0.0.1:8080:80" (local only), "53:53/udp"
exposethe port is visible to other services but not to the host (serves as documentation)
networkswhich networks to attach the service to
extra_hostsextra entries in the container's /etc/hosts

Variables and data

KeyWhat it defines
environmentvariables: as a mapping KEY: value or a list - KEY=value
env_filea file (or list of files) with KEY=value lines
volumesvolume_name:/path — a volume; ./dir:/path — a host directory; :ro — read-only
tmpfsin-memory directories
secretswhich top-level secrets to attach

Order and health

KeyWhat it defines
depends_on: [db]short form: start after the db container
depends_on: {db: {condition: …}}long form with a condition (see below)
healthcheck.testthe check command: ["CMD", "prog", "arg"] or ["CMD-SHELL", "string for sh"]
healthcheck.interval / timeout / retrieshow often to check / how long to wait for a response / how many failures in a row mean "unhealthy"
healthcheck.start_periodstartup time during which failures don't count yet
deploy.resources.limitscpus and memory limits
logginglog driver and its options (max-size)

Conditions in depends_on:

conditionWait until the dependency…
service_startedhas started (same as the short form)
service_healthybecomes healthy — the dependency needs a healthcheck
service_completed_successfullyexits with code 0 (migrations, data preparation)

Variable substitution

Values can reference environment variables and the .env file next to the compose file: ${TAG}, ${TAG:-latest} — a default value, ${TAG:?TAG must be set} — an error if the variable is missing. $$ is a literal $.

Commands (where Docker is installed)

CommandWhat it does
docker compose up -dcreate and start everything in the background; --build — rebuild images
docker compose downstop and remove containers and networks; -v — volumes too
docker compose psservice status
docker compose logs -f servicelogs, waiting for new ones
docker compose exec service sha shell in a running container
docker compose run --rm service commanda one-off container of the service
docker compose configthe final file after variable substitution and validation
docker compose restart / stop / pull / buildrestart / stop / pull / build images

Examples

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10

  web:
    image: nginx:${NGINX_TAG:-1.27}
    ports:
      - "8080:80"
    volumes:
      - ./site:/usr/share/nginx/html:ro
    environment:
      - BACKEND_HOST=db
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

volumes:
  db-data:
# validate the file against the schema (in the sandbox)
yamlschema compose compose.yaml && echo OK

# a typo in a key gives a clear error, for example:
# compose.yaml: services/web: Unevaluated properties are not allowed ('enviroment' was unexpected)

# look at the file's structure: service names and their ports
yq '.services | keys' compose.yaml
yq '.services.web.ports' compose.yaml

# where Docker is available:
# docker compose config     # the final file after variable substitution
# docker compose up -d      # bring it up in the background
# docker compose logs web   # logs of one service
# docker compose down       # stop and remove the containers

Pitfalls

  • Short-form depends_on only waits for the container to start, not for the program inside to be ready. The database may still be initializing while the application is already trying to connect. To wait for readiness you need a healthcheck on the dependency and condition: service_healthy on the dependent service.
  • depends_on only affects startup through compose. If the dependency crashes later, the dependent service won't know: the application itself must be able to reconnect.
  • Quote ports. Some YAML 1.1 parsers read 22:22 as a base-60 number (1342). The string "22:22" is unambiguous.
  • The order in ports is host:container. "8080:80" opens port 8080 on the host and forwards it to 80 inside the container, not the other way round. Without an address the port listens on all host interfaces.
  • A named volume must be declared in the top-level volumes:. A path starting with ./ or / is a host directory, not a volume.
  • Inside the network use the service name and the container port (db:5432), not localhost or the host port: localhost in a container is the container itself.
  • environment beats env_file. If a variable is set in both places, environment wins.
  • CMD and CMD-SHELL differ. ["CMD", "pg_isready -U postgres"] looks for a program with spaces in its name. Pass a string with arguments via CMD-SHELL or split it into list items.
  • The schema catches typos in keys, not meaning. yamlschema won't check whether a volume is declared, whether the restart value is valid, whether the image exists or whether the port is free.

See also

kubectl · yq · gitlab-ci · psql