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
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
  1. 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_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.