Compose Basics
Real applications are rarely one container. A web shop might need an API, a PostgreSQL database, a Redis cache and a background worker. Starting them with four long docker run commands, in the right order, on the right network, is error-prone. Docker Compose describes the whole application in one YAML file and manages it with a few commands.
# compose.yaml
services:
api:
build: .
ports:
- "8000:8000"
environment:
DATABASE_URL: postgres://shop:dev@db:5432/shop
REDIS_URL: redis://cache:6379/0
depends_on:
- db
- cache
db:
image: postgres:17
environment:
POSTGRES_USER: shop
POSTGRES_PASSWORD: dev
volumes:
- pgdata:/var/lib/postgresql/data
cache:
image: redis:8
volumes:
pgdata:docker compose up -d # build if needed, create network + volume, start everything
docker compose ps # status of this project's containers
docker compose logs -f api # follow one service's logs
docker compose exec db psql -U shop
docker compose down # stop and remove containers and the network (volumes stay)
docker compose down -v # ...and remove the volumes tooSample output of docker compose up -d:
[+] Running 5/5
✔ Network shop_default Created
✔ Volume "shop_pgdata" Created
✔ Container shop-cache-1 Started
✔ Container shop-db-1 Started
✔ Container shop-api-1 StartedWhat Compose does for you
- A project name, by default the folder name (
shop), prefixes everything it creates:shop_default,shop_pgdata,shop-api-1. Two copies of the same app in different folders don't collide. - A default network that all services join. Each service is reachable by its service name (
db,cache), exactly like a user-defined network in the Networks lesson. - Declarative updates: run
docker compose up -dagain after editing the file and Compose only recreates the services whose configuration changed.
The model reads a compose file (with PyYAML, the same YAML parser many tools use) and lists the resources Compose would create:
import yaml
COMPOSE = """
services:
api:
build: .
ports: ["8000:8000"]
depends_on: [db, cache]
db:
image: postgres:17
volumes: ["pgdata:/var/lib/postgresql/data"]
cache:
image: redis:8
volumes:
pgdata: {}
"""
project = "shop"
spec = yaml.safe_load(COMPOSE)
print(f"network {project}_default")
for name in spec.get("volumes", {}):
print(f"volume {project}_{name}")
for name, service in spec["services"].items():
image = service.get("image") or f"{project}-{name} (built from {service['build']})"
ports = ", ".join(service.get("ports", [])) or "-"
print(f"container {project}-{name}-1 image={image} ports={ports}")network shop_default
volume shop_pgdata
container shop-api-1 image=shop-api (built from .) ports=8000:8000
container shop-db-1 image=postgres:17 ports=-
container shop-cache-1 image=redis:8 ports=-
The service keys you'll use most
| Key | docker run equivalent |
Example |
|---|---|---|
image |
the image name | image: postgres:17 |
build |
docker build |
build: . or build: {context: ., target: prod} |
ports |
-p |
- "127.0.0.1:5432:5432" |
environment / env_file |
-e / --env-file |
LOG_LEVEL: debug |
volumes |
-v |
- ./src:/app/src |
command / entrypoint |
override CMD / ENTRYPOINT | command: ["npm", "run", "dev"] |
depends_on |
(start order) | - db |
restart |
--restart |
restart: unless-stopped |
healthcheck |
--health-cmd … |
(next lesson) |
Tip: quote port mappings (
"8000:8000"). YAML 1.1 parsers read unquoted values like22:22as base-60 numbers (1342), a famous gotcha.
import yaml
print(yaml.safe_load("ports: [22:22, 8000:8000, '22:22']")){'ports': [1342, '8000:8000', '22:22']}
PyYAML, like many YAML 1.1 parsers, turns 22:22 into the number 1342 (22 × 60 + 22). Quoting avoids the problem everywhere.
Scaling and service names
docker compose up -d --scale worker=3 runs three containers for one service: shop-worker-1, -2, -3. The service name worker then resolves to all three IPs (DNS round-robin). Services that publish a fixed host port can't be scaled that way, since only one container can bind 8000 on the host.
def container_names(project, services, scale):
names = []
for service, publishes_port in services.items():
count = scale.get(service, 1)
if publishes_port and count > 1:
names.append(f"error: {service} publishes a fixed host port and can't run {count} replicas")
continue
names += [f"{project}-{service}-{i}" for i in range(1, count + 1)]
return names
for line in container_names("shop", {"api": True, "worker": False, "db": False}, {"worker": 3}):
print(line)
print()
for line in container_names("shop", {"api": True}, {"api": 2}):
print(line)shop-api-1
shop-worker-1
shop-worker-2
shop-worker-3
shop-db-1
error: api publishes a fixed host port and can't run 2 replicas
Compose file names and versions
Compose looks for compose.yaml (preferred), compose.yml, docker-compose.yaml or docker-compose.yml. The old top-level version: "3.8" line is obsolete and ignored by Compose v2; leave it out.
Go deeper: the Docker Compose course covers every part of the compose file in depth, from the compose file to override files and production.
Test yourself
In a compose project, how does the api service reach the db service?
- localhost:5432
- By the service name, e.g. db:5432, on the project's default network
- Only through a published host port
- By the container ID
What does docker compose down remove by default?
- Containers, networks and named volumes
- Containers and the default network, but not named volumes
- Only containers
- Images
Why should port mappings in YAML be quoted?
- Compose requires strings everywhere
- Some YAML parsers read values like 22:22 as base-60 numbers
- Quotes make ports public
- To disable EXPOSE