The compose.yml File
The compose.yml file lists services, images, ports, environment and volumes in a readable YAML structure.
Syntax
services:
name:
image: image:tag
ports:
- "host:container"The heart of Compose is the compose.yml file, written in YAML. Its top-level services key lists each container in your app.
Common service keys
image— the image to use, orbuildto build from a Dockerfile.ports— port mappings, like"8080:80".environment— environment variables.volumes— mounts for persistent data.depends_on— startup order between services.
YAML basics
YAML uses indentation (spaces, never tabs) to show structure. Lists start with a dash, and key-value pairs use a colon.
Example
services:
web:
image: nginx:1.27-alpine
ports:
- "8080:80"
volumes:
- ./site:/usr/share/nginx/html:ro
environment:
- TZ=UTCWhen to use it
- A team checks compose.yml into version control so the exact service configuration, port mappings, and environment variables are documented and reproducible.
- A developer adds a new service to compose.yml to integrate a Redis cache without touching the other services.
- A DevOps engineer uses environment variable substitution in compose.yml so the same file works for both local dev and CI.
More examples
Minimal compose.yml for a web app
The simplest valid compose file: one service with an image, a port mapping, and a bind mount.
services:
web:
image: nginx:alpine
ports:
- "8080:80"
volumes:
- ./html:/usr/share/nginx/html:roService built from a Dockerfile
Uses build instead of image so Compose builds the image from the local Dockerfile before starting the service.
services:
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- PORT=3000Use .env file with Compose
Compose automatically reads a .env file and substitutes variables, keeping secrets out of compose.yml.
# compose.yml
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: ${DB_NAME}
# .env file:
# DB_PASSWORD=secret
# DB_NAME=myapp
Discussion