CodePark/ questions / Environment, config & secrets
START PRACTICINGPRACTICE
Backend question · Docker › Environment, config & secrets

What are the ways to pass environment variables to a container, and what does a .env file next to compose.yaml actually do?

There are three main ways to pass environment variables to a container:

  • CLI: use -e NAME=value for one variable, or --env-file app.env to load a file of them.
  • Compose: use the environment attribute to write values in the Compose file, or env_file to load a file into the container.
  • Image: the Dockerfile can set default values with ENV.

A .env file in the project directory does something different. Compose reads it for variable interpolation. This means Compose fills in ${VAR} references inside compose.yaml with values from .env.

Compose does not pass .env into containers automatically. A variable reaches a container only in two cases:

  • The Compose file references it in environment.
  • The Compose file loads the file through env_file.

Keep .env files out of Git with .gitignore. Keep them out of the image with .dockerignore.

  • On the CLI, use -e and --env-file.
  • In Compose, use environment and env_file.
  • Compose uses .env to fill in ${VAR} references in compose.yaml.
  • Compose does not put .env values into containers automatically.