✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.3.4 Service Environment Config

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

Service environment config is the complete set of mechanisms a Compose service can use to receive environment variables — inline values, host-environment substitution, and dedicated environment files — together providing flexible, layered control over a service's runtime configuration.

Inline Values Within the Service Definition

The simplest approach lists each variable directly within the service's environment field.

services:
  api:
    environment:
      - LOG_LEVEL=debug
      - PORT=8080
Substituting Values From the Host Environment

A variable's value can be sourced from the host's own environment at the time Compose runs, useful for values that shouldn't be hardcoded.

services:
  api:
    environment:
      - API_KEY=${API_KEY}
Loading Variables From a Dedicated File

For a larger set of variables, an external file referenced through env_file avoids needing to list each one individually within the Compose file.

services:
  api:
    env_file:
      - .env.api
DATABASE_URL=postgres://db:5432/app
LOG_LEVEL=debug
Combining Multiple Sources, With a Defined Precedence

A service can use several of these mechanisms together, with Compose applying a defined precedence order when the same variable is specified through more than one source.

services:
  api:
    env_file:
      - .env.api
    environment:
      - LOG_LEVEL=debug

Generally, a value set directly under environment takes precedence over the same variable's value sourced from an env_file, useful for overriding a specific value from the file without needing to modify that file itself.

Why Service Environment Config Matters

Together, these mechanisms provide the flexibility needed to configure a service's runtime behavior appropriately across a wide range of scenarios, from a handful of simple inline values to many variables managed through dedicated, environment-specific files.

Content in this section