As your projects grow more complex, a single file.envcan quickly become cumbersome.DockerCompose offers a practical solution: env_file, which allows you to load additional environment variable files for a specific service.
How does it work?
.envis always loaded automatically byDockerCompose, even if you don’t specify it.env_fileallows you to add one or more service-specific files.restartThese files can only contain environment variables (no `, `,imageor other YAML directives).
Example project structure:
project/
├─ docker-compose.yml
├─ .env
├─ db.env
├─ app.envFiledb.env:
DB_PASSWORD=supersecret
DB_NAME=monprojet
Fileapp.env:
APP_ENV=production
APP_DEBUG=false
In thedocker-compose.yml :
services:
db:
image: mariadb:10.11
env_file:
- db.env
environment:
MYSQL_USER: ${DB_USER} # interpolation depuis .env
php:
image: php:8.2-apache
env_file:
- app.env
Key points to remember
- .env vs env_file
| Element | Loaded automatically? | What can it contain? | Scope |
|---|---|---|---|
.env | Yes | Any type of variable (env, image, tag, restart, ports via interpolation) | Global to the entire Docker Compose |
env_file | No, must be declared | Only environment variables | Per service |
- Variable priority order
- Variables in docker-compose.yml (via
environment:) → highest priority. Variables inenv_file→ intermediate priority. Variables in.env→ lowest priority
DB_PASSWORDis defined in.envand indb.env,DockerCompose will use the value fromdb.env. - Variables in docker-compose.yml (via
- Mixed usage
.envcan always be used to interpolate parameters such asrestart: ${RESTART_POLICY}orimage: myimage:${TAG}.env_fileis especially useful for separating secrets or service-specific configurations.
📌 Key takeaway:
.env→ the global vault, useful for interpolation and general configuration.env_file→ Service-specific files to keep configurations clean and separate.- Variables declared directly in the YAML >
env_file>.env.