Sub topic 3
Parameterizing Compose for Different Environments
Assume you know basic Docker images, containers, volumes, YAML, and shell environment variables. This chapter focuses on how Compose chooses values before it starts containers.
Variables and env files
Compose interpolates variables in YAML from the shell, a project .env file, or a file passed with --env-file. Use a required value for secrets:
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD}Run it with a separate variable file:
docker compose --env-file .env.dev up -dA default is useful for non-secret settings:
environment:
LOG_LEVEL: ${LOG_LEVEL:-info}env_file has a different purpose. It passes variables into a container. It does not generally provide values for Compose's own interpolation.
services:
web:
env_file:
- .env.webChoosing overrides and profiles
Use an override file when an environment changes existing service definitions. Use a profile when a service is optional, such as Adminer, a debugger, or a migration tool.
flowchart TD
Base[compose.yaml] --> Dev[Development override]
Base --> Prod[Production file]
Base --> Optional[Optional profiles]
Dev --> Result[Selected Compose configuration]
Prod --> Result
Optional --> ResultCaption and alt text belong outside Mermaid's source:
Use both when development needs changed defaults and optional tools:
docker compose --profile debug up -dReplacing inherited values
Mappings usually merge by key. A later scalar replaces an earlier scalar. Lists can append, which may leave unwanted ports or volumes. Compose versions supporting merge tags can replace or remove values:
services:
web:
ports: !override
- "9000:8000"
environment:
DEBUG: !reset nullReuse with `include` and `extends`
Use include to assemble separate Compose projects or shared fragments. Use extends to reuse a service definition, then customize it. These features reduce duplication, but they add file relationships that can make debugging harder. Prefer ordinary override files when a simple environment layer is enough.
Production and CI practices
Keep production selection explicit:
docker compose -f compose.yaml -f compose.prod.yaml config
docker compose -f compose.yaml -f compose.prod.yaml up -dCI should use pinned image tags, injected secrets, and a clean, explicit file list. Check the rendered configuration before deployment.
Troubleshooting
Run docker compose config to inspect interpolation, merges, and profiles:
docker compose --env-file .env.test --profile tools configIf a value is missing, check whether it belongs to Compose interpolation or container runtime environment. If a list contains duplicates, inspect every selected file and use !override where supported.
Exercise
Which mechanism should you use for an optional database browser that should not start in production?
Show answer
Put the database browser service in a profile and activate that profile only in development.