Compose environment files and interpolation
- Version
- 29
- Review
- Draft
Summary#
Compose reads .env or a CLI --env-file to resolve variables in the Compose file. A service's env_file adds variables to its containers. Values explicitly set under environment override that service's env_file.
Syntax#
docker compose --env-file ./project.env config
docker compose --env-file ./project.env up --detach
Example#
The example uses a local alpine:3 image.
(
set -eu
project="dlr-docker-commands-compose-env-$$"
dir=$(mktemp -d)
compose() {
docker compose --progress quiet --project-name "$project" \
--file "$dir/compose.yaml" --env-file "$dir/project.env" "$@"
}
trap 'compose down --timeout 1 >/dev/null 2>&1 || true; rm -rf -- "$dir"' EXIT
unset DLREF_MODE DLREF_LOCAL_ONLY
printf 'DLREF_MODE=chosen\nDLREF_LOCAL_ONLY=compose\n' > "$dir/project.env"
printf 'DLREF_MODE=fallback\nDLREF_REGION=west\n' > "$dir/app.env"
cat > "$dir/compose.yaml" <<'EOF'
services:
app:
image: alpine:3
pull_policy: never
env_file: app.env
environment:
DLREF_MODE: ${DLREF_MODE:?set DLREF_MODE}
EOF
compose config --quiet
compose run --rm -T app sh -c \
'printf "mode=%s region=%s local=%s\n" "$DLREF_MODE" "$DLREF_REGION" "${DLREF_LOCAL_ONLY-unset}"'
)
Expected output#
mode=chosen region=west local=unset
Common mistakes#
An entry in the project's .env does not automatically become a container variable. Reference it under environment or list a separate service env_file. Shell variables can override values from the project's environment file during interpolation.
Version applicability#
Checked with Docker Compose 5 and Docker Engine 29. Compose CLI interpolation from .env is unavailable with docker stack deploy.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0