How to use environment variables in Docker Compose?

· Category: Docker

Short answer

Docker Compose supports environment variables through the environment key, .env files, and shell exports. This flexibility lets you configure services per environment without modifying the Compose file.

Steps

  1. Define variables directly in docker-compose.yml.
  2. Create a .env file in the same directory.
  3. Export variables in your shell before running Compose.
  4. Use ${VAR} syntax for variable substitution in the Compose file.

Example

services:
  app:
    image: myapp
    environment:
      - DATABASE_URL=${DATABASE_URL}
      - DEBUG=true

.env file:

DATABASE_URL=postgres://db:5432/app

Tips

  • Use .env for non-sensitive values; use Docker secrets for passwords.
  • Set default values with ${VAR:-default}.
  • Require variables with ${VAR:?error message}.

Common issues

  • .env must be in the same directory as the Compose file by default.
  • Shell variables take precedence over .env file values.
  • Boolean values in YAML may be misinterpreted; quote them like "true".