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.env
Filedb.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 in**env_file** β intermediate priority. Variables in**.env** β lowest priority πΉ Example: ifDB_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.