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
- Define variables directly in
docker-compose.yml. - Create a
.envfile in the same directory. - Export variables in your shell before running Compose.
- 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
.envfor non-sensitive values; use Docker secrets for passwords. - Set default values with
${VAR:-default}. - Require variables with
${VAR:?error message}.
Common issues
.envmust be in the same directory as the Compose file by default.- Shell variables take precedence over
.envfile values. - Boolean values in YAML may be misinterpreted; quote them like
"true".