✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.2.1.5 Service Environment Field

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

The environment field within a Compose service supplies environment variables directly to that service's container, providing a way to configure application behavior without modifying the underlying image.

Setting Variables as a List

The most common form lists each variable as a KEY=value string.

services:
  api:
    environment:
      - LOG_LEVEL=debug
      - PORT=8080
      - NODE_ENV=development
Setting Variables as a Mapping

The same configuration can alternatively be expressed as a key-value mapping, which some find more readable, particularly for values that themselves might contain characters that complicate the list-string form.

services:
  api:
    environment:
      LOG_LEVEL: debug
      PORT: "8080"
      NODE_ENV: development
Referencing Host Environment Variables

A variable's value can be substituted from the host's own environment, useful for secrets or values that shouldn't be hardcoded directly in the Compose file.

services:
  api:
    environment:
      - API_KEY=${API_KEY}
export API_KEY=secret123
docker compose up -d
Distinguishing Environment From Env File

For a large number of variables, env_file references an external file instead of listing each variable individually within the Compose file itself, though both ultimately achieve the same effect of supplying environment variables to the container.

services:
  api:
    env_file:
      - .env.api
Why the Environment Field Matters

The environment field is one of the most commonly used mechanisms for configuring a service's runtime behavior, supporting everything from simple feature flags to passing through sensitive values sourced from the host, without requiring the underlying image itself to be modified for different configuration needs.