7.3: Multi-file management: Use env_file to separate configurations

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?

  • .env is always loaded automatically byDockerCompose, even if you don’t specify it.
  • env_file allows 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

  1. .env vs env_file
ElementLoaded automatically?What can it contain?Scope
.envYesAny type of variable (env, image, tag, restart, ports via interpolation)Global to the entire Docker Compose
env_fileNo, must be declaredOnly environment variablesPer service
  1. Variable priority order
    • Variables in docker-compose.yml (via environment:) → highest priority. Variables inenv_file → intermediate priority. Variables in.env → lowest priority
    🔹 Example: ifDB_PASSWORD is defined in.env and in db.env,DockerCompose will use the value from db.env.
  2. Mixed usage
    • .env can always be used to interpolate parameters such asrestart: ${RESTART_POLICY} or image: myimage:${TAG}.
    • env_file is 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.