How to Use Environment Variables in Docker Compose
In
docker-compose.yml, use the environment key under a service to set environment variables as key-value pairs. These variables configure the container's runtime environment and can be defined inline or loaded from an external .env file.Syntax
The environment section in a docker-compose.yml file defines environment variables for a service. You can specify variables as a list or a map of key-value pairs.
- List format: Each item is
KEY=VALUE. - Map format: Use
KEY: VALUEpairs.
These variables are passed to the container and can be used by the application inside.
yaml
services:
app:
image: myapp:latest
environment:
- DEBUG=true
- PORT=8080
# Or using map format
services:
app:
image: myapp:latest
environment:
DEBUG: "true"
PORT: "8080"Example
This example shows a simple docker-compose.yml file that sets environment variables for a web service. The container prints the environment variables when it starts.
yaml
version: '3.8' services: web: image: alpine command: sh -c "echo DEBUG=$DEBUG && echo PORT=$PORT" environment: DEBUG: "true" PORT: "3000"
Output
DEBUG=true
PORT=3000
Common Pitfalls
Common mistakes when using environment variables in Docker Compose include:
- Using incorrect indentation or syntax in
docker-compose.yml. - Forgetting to quote string values that look like numbers or booleans, which can cause parsing issues.
- Expecting environment variables defined in the host shell to automatically pass into containers without explicitly defining them.
- Not using a
.envfile when you want to separate secrets or configuration from the compose file.
yaml
services:
app:
image: myapp
environment:
- DEBUG=true
- PORT=3000
# Wrong: missing quotes for boolean value might cause issues
services:
app:
image: myapp
environment:
DEBUG: "true" # Should be quoted
PORT: "3000" # Should be quotedQuick Reference
| Feature | Description | Example |
|---|---|---|
| Inline environment variables | Set variables directly in docker-compose.yml | environment: - KEY=value - DEBUG=true |
| Map format | Use key-value pairs for clarity | environment: KEY: value DEBUG: "true" |
| Using .env file | Place variables in a .env file to load automatically | KEY=value DEBUG=true |
| Referencing host variables | Use ${VAR} syntax to inject host env vars | environment: DEBUG: "${DEBUG}" |
Key Takeaways
Use the environment key in docker-compose.yml to set container environment variables.
Specify variables as a list of KEY=VALUE or as a map of key: value pairs.
Quote string values to avoid parsing errors, especially for booleans and numbers.
Use a .env file to keep environment variables separate and secure.
Host environment variables can be injected using ${VAR} syntax in the compose file.