There are three main ways to pass environment variables to a container:
- CLI: use
-e NAME=valuefor one variable, or--env-file app.envto load a file of them. - Compose: use the
environmentattribute to write values in the Compose file, orenv_fileto 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
-eand--env-file. - In Compose, use
environmentandenv_file. - Compose uses
.envto fill in${VAR}references incompose.yaml. - Compose does not put
.envvalues into containers automatically.
Read more