Sub topic 1
A quick base Compose file
Prerequisites
Assume you can read simple YAML, understand images and containers, and have run docker compose up and docker compose down. Compose is Docker’s tool for defining and running related containers from a YAML file.
A base file should contain settings shared by every environment:
# compose.yaml
services:
web:
image: example/web:1.0
ports:
- "8000:8000"
environment:
LOG_LEVEL: info
depends_on:
- db
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:The ${DB_PASSWORD:?set DB_PASSWORD} expression requires the variable to exist. This keeps the password out of the file.
Why environments need different settings
Development may build the image locally, mount source code, and enable verbose logs. Test may use temporary data and extra test services. Production may use a published image, restart policies, quieter logs, and no source mounts.
Keeping these differences in separate files reduces accidental production changes.
flowchart TD
Base[compose.yaml] --> Dev[Development settings]
Base --> Test[Test settings]
Base --> Prod[Production settings]Adding development settings with compose.override.yaml
When you run Compose without -f, Compose automatically loads compose.yaml and then compose.override.yaml, if that file exists.
# compose.override.yaml
services:
web:
build: .
volumes:
- ./src:/app/src
environment:
LOG_LEVEL: debugThe override changes only development settings. The base file still supplies the database and shared configuration.
Choosing files explicitly with `-f` and COMPOSE_FILE
Use -f to select files and their order. Later files override or extend earlier files:
# Uses compose.yaml and compose.override.yaml automatically
docker compose up -d
# Uses only the files listed here
docker compose -f compose.yaml -f compose.prod.yaml up -d
# The same selection on Linux or macOS
COMPOSE_FILE=compose.yaml:compose.prod.yaml docker compose up -dWhen -f is present, list every file you need. Compose does not add the automatic override implicitly.
How Compose merges files
Compose generally merges mappings by key, replaces scalar values, and appends many list values. For example, the later environment mapping can replace LOG_LEVEL, while an added port may join the existing list. Some fields, such as command, are replaced rather than appended. Check the final result instead of guessing.
docker compose -f compose.yaml -f compose.prod.yaml configExercise
Which command selects the base and production files without loading the development override?
Show answer
docker compose -f compose.yaml -f compose.prod.yaml up -d