9.3.4.3 Compose Variable Interpolation
A focused guide to Compose Variable Interpolation, connecting core concepts with practical Docker and container operations.
Compose variable interpolation is the process by which Compose substitutes variable references — written as ${VARIABLE_NAME} — within the Compose file itself, sourcing their values from the host's environment or a .env file located alongside the Compose file.
Basic Variable Substitution
A variable reference anywhere within the Compose file is replaced with the corresponding value before Compose actually processes the file's configuration.
services:
api:
image: myapi:${APP_VERSION}
export APP_VERSION=2.3.0
docker compose up -d
This results in Compose actually using myapi:2.3.0, with the substitution happening before the configuration is applied.
Using a .env File for Interpolation Values
Rather than relying on variables already set in the host's shell environment, a .env file in the same directory as the Compose file provides default values for interpolation automatically.
APP_VERSION=2.3.0
LOG_LEVEL=debug
services:
api:
image: myapi:${APP_VERSION}
environment:
- LOG_LEVEL=${LOG_LEVEL}
Why This Differs From the Env File Field on a Service
This .env file convention is distinct from a service's own env_file field — the .env file specifically supports interpolation within the Compose file's own structure, while env_file supplies environment variables directly to a service's runtime container.
services:
api:
env_file:
- .env.api
Providing a Default Value for an Unset Variable
A default can be specified directly within the interpolation syntax, used if the referenced variable isn't otherwise set.
services:
api:
image: myapi:${APP_VERSION:-latest}
Why Compose Variable Interpolation Matters
This mechanism allows a single Compose file to flexibly adapt based on external values, supporting different versions, environments, or configurations without needing separate, duplicated Compose files for each variation.