Opscraft
Docker Compose · Lesson 3 of 10 · 3 min read

Variables and configuration

Two different kinds of "environment"

People mix these up constantly:

  1. Interpolation variables — ${TAG} inside the compose file, substituted when Compose parses the file. Sources: your shell environment, then the .env file in the project directory (or --env-file).
  2. Container environment — variables set inside the container via environment: and env_file:.

The .env file is not passed into containers automatically; it only feeds interpolation. env_file: .env passes it into a container explicitly.

Interpolation syntax

image: shop-api:${TAG}              # empty string if unset (with a warning)
image: shop-api:${TAG:-dev}         # default if unset OR empty
image: shop-api:${TAG-dev}          # default only if unset
image: shop-api:${TAG:?TAG is required}   # fail with an error if unset/empty
command: echo $$HOME                # $$ = literal $, evaluated in the container

Precedence for container environment

From highest to lowest: values set with docker compose run -e, then environment:, then env_file:, then the image's ENV. Shell variables beat .env for interpolation.

Use docker compose config to print the fully resolved file — the fastest way to debug "why does my container have the wrong value?".

Enlarge diagramdocker compose run -e KEY=…one-off override on the command lineenvironment:in the service definitionenv_file:a file listed for the serviceImage ENVset in the Dockerfilewinsloses
Figure 1. Where a container's environment variables come from, highest priority first.
Swipe sideways to see all of it, or tap to open it full screen.

Secrets

Compose secrets: mount a file read-only at /run/secrets/<name>. Many official images support *_FILE variables (POSTGRES_PASSWORD_FILE) for this. Locally the source is just a file, so this isn't encryption — but it keeps secrets out of docker inspect output and the compose file, and builds the habit of file-based secrets that maps to Kubernetes and Swarm.

Watch out: a password committed in compose.yaml or .env is leaked even after you delete it — it lives in Git history. Remove it, rotate the credential, and add .env to .gitignore (commit a .env.example instead).