docker compose environment variables — how to set

# docker-compose.yml — inline values
services:
  app:
    image: my-app
    environment:
      NODE_ENV: production
      PORT: "3000"

# Or load from a file
    env_file:
      - .env

You need to configure services differently per environment (dev / staging / prod) without hardcoding values in the Compose file.

Variable substitution from .env

Compose automatically reads .env in the project directory for variable substitution in the YAML:

# .env
POSTGRES_VERSION=16
DB_NAME=myapp

# docker-compose.yml
services:
  db:
    image: postgres:{POSTGRES_VERSION}
    environment:
      POSTGRES_DB: {DB_NAME}

Override with -e at runtime

docker compose run -e NODE_ENV=test app npm test

Per-environment override files

# Base: docker-compose.yml
# Override for prod: docker-compose.prod.yml

docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d

Pass host variables into compose

# In docker-compose.yml — no value = read from host shell
environment:
  - SECRET_KEY   # value comes from: export SECRET_KEY=... on the host