How to Use env_file in Docker Compose for Environment Variables
Use the
env_file option in your docker-compose.yml to specify a file containing environment variables. Docker Compose loads these variables into the container, making configuration simple and clean.Syntax
The env_file option in docker-compose.yml points to one or more files containing environment variables. Each file should have lines in the format KEY=VALUE. This option is placed under the service definition.
Example parts:
env_file:key to specify environment files- ./myenv.envpath to the env file
yaml
services:
app:
image: myapp:latest
env_file:
- ./myenv.envExample
This example shows a Docker Compose file using env_file to load environment variables from app.env. The container prints the variable GREETING to demonstrate it works.
yaml
version: '3.8' services: hello: image: alpine env_file: - app.env command: sh -c "echo \"$GREETING\""
Output
Hello from env_file!
Common Pitfalls
Common mistakes when using env_file include:
- File path is incorrect or file does not exist.
- Environment file has spaces around
=which are not allowed. - Using
environmentandenv_filewith conflicting variables;environmentoverridesenv_file. - Not restarting containers after changing the env file.
Example of wrong and right usage:
yaml
services:
app:
image: myapp
env_file:
- ./wrong path.env # Wrong: path with space or file missing
services:
app:
image: myapp
env_file:
- ./correct_path.env # Right: correct path and file existsQuick Reference
| Option | Description | Notes |
|---|---|---|
| env_file | Specifies file(s) with environment variables | Supports multiple files as a list |
| environment | Defines environment variables inline | Overrides variables from env_file if duplicated |
| File format | KEY=VALUE per line | No spaces around '='; comments start with '#' |
| Variable precedence | environment > env_file > Dockerfile ENV | Last wins if duplicated |
Key Takeaways
Use
env_file in docker-compose.yml to load environment variables from a file.Ensure the env file path is correct and the file format is KEY=VALUE without spaces around '='.
Variables defined in
environment override those in env_file.Restart containers after changing env files to apply updates.
You can specify multiple env files as a list under
env_file.