✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.3.4.2 Environment File Loading

A focused guide to Environment File Loading, connecting core concepts with practical Docker and container operations.

Environment file loading is the process by which Compose reads a referenced env_file and supplies its contents as environment variables to a service's container, providing a convenient way to manage a larger set of variables without listing each one individually within the Compose file.

Referencing an Environment File

The env_file field on a service points to one or more files containing variable definitions.

services:
  api:
    env_file:
      - .env.api
DATABASE_URL=postgres://db:5432/app
LOG_LEVEL=debug
CACHE_TTL=3600

Every variable defined in this file becomes available inside the api service's container, exactly as if each had been listed individually under environment.

Loading Multiple Environment Files

Several files can be referenced together, with later files in the list taking precedence over earlier ones for any variable defined in more than one.

services:
  api:
    env_file:
      - .env.defaults
      - .env.local

This pattern allows a base set of defaults to be layered with local, environment-specific overrides.

Comment and Formatting Conventions Within an Env File

An environment file follows simple KEY=value formatting, with blank lines and lines beginning with # treated as comments and ignored.

# Database configuration
DATABASE_URL=postgres://db:5432/app

# Logging
LOG_LEVEL=debug
Why Env Files Should Often Be Excluded From Version Control

A file containing environment-specific or sensitive values should typically be excluded from version control, with a committed template documenting the expected variables without their actual values.

.env.local
Why Environment File Loading Matters

This mechanism provides a convenient, organized way to manage a substantial number of environment variables, keeping the Compose file itself focused while still supplying services with everything they need to run correctly.