Four ways to get a .env into a container
| Method | Where values live | Secrets OK? | Best for |
|---|---|---|---|
env_file: .env (Compose) | the .env on the host | yes, if .env is not committed | local dev, single servers |
environment: block (Compose) | compose.yaml | no, if compose.yaml is in git | non-secret defaults |
docker run --env-file .env | the .env on the host | yes | one-off containers, CI |
Dockerfile ENV | the image itself | no | defaults baked into the image |
Kubernetes Secret + envFrom | etcd (base64) | yes, with RBAC and encryption at rest | clusters |
This converter produces the environment:, ENV and Secret variants. For the common local setup, reference the file instead and keep it out of git, see how to hide .env from git.
Quoting rules that break Docker setups
- YAML booleans:
true,false,yes,no,on,offunquoted are booleans; Compose refuses them inenvironment:. Quoted they are strings. - Interpolation: Compose replaces
$VARand${VAR}in compose.yaml with values from your shell or the project.env. Write$$for a literal dollar sign. - Dockerfile ENV: also substitutes
$VAR; escape it as\$. Values with spaces need double quotes. - `docker run --env-file`: takes everything after
=literally, quotes included.KEY="x"gives the value"x"with the quotes.
If you are not sure what a loader will make of your file, run it through the .env validator first. For multi-framework compose stacks, the Docker .env generator has a full example.
Creating the Kubernetes Secret from the command line
# straight from the .env, without writing YAML yourself kubectl create secret generic app-env --from-env-file=.env # or render YAML for review / GitOps (then seal or encrypt it) kubectl create secret generic app-env --from-env-file=.env \ --dry-run=client -o yaml > app-env.yaml
containers:
- name: app
envFrom:
- secretRef:
name: app-envPods read environment variables only at start. After changing the Secret, run kubectl rollout restart deployment/app. The comparison .env vs Kubernetes Secrets covers when each approach fits.