0
0
DockerHow-ToBeginner · 3 min read

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.env path to the env file
yaml
services:
  app:
    image: myapp:latest
    env_file:
      - ./myenv.env
💻

Example

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 environment and env_file with conflicting variables; environment overrides env_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 exists
📊

Quick Reference

OptionDescriptionNotes
env_fileSpecifies file(s) with environment variablesSupports multiple files as a list
environmentDefines environment variables inlineOverrides variables from env_file if duplicated
File formatKEY=VALUE per lineNo spaces around '='; comments start with '#'
Variable precedenceenvironment > env_file > Dockerfile ENVLast 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.