🐳 The .env File Is Right There – The Container Never Sees Its Values
A .env file sits in the project directory with all the right variables defined, docker-compose up runs without any error, and inside the running container, those same environment variables are simply missing – the application falls back to defaults or fails outright looking for configuration that should have been there.
🐞 The Problem
# .env
DATABASE_URL=postgres://user:pass@db:5432/myapp
# docker-compose.yml
services:
app:
image: myapp:latest
# no "env_file" or "environment" section referencing .env at all!
$ docker exec app printenv DATABASE_URL
(nothing - the variable simply isn't set inside the container)
🔍 Why This Happens
A .env file sitting next to docker-compose.yml is automatically
used by Docker Compose ONLY for variable SUBSTITUTION within the
compose file itself (like ${DATABASE_URL} referenced inside
docker-compose.yml) - it is not automatically passed through into
the container's own environment unless the compose file explicitly
says so, via an "env_file" or "environment" section. These are two
genuinely separate mechanisms that happen to share the same file by
convention, and assuming one implies the other is the actual root
cause here.
✅ The Fix: Explicitly Reference env_file or environment in Compose
- Add an explicit
env_file: .enventry under the service in docker-compose.yml – this is what actually passes every variable from that file into the container’s environment, distinct from compose-file-only substitution. - For just a specific handful of variables,
environment:with explicit key-value pairs (optionally referencing${VAR}substitution from the .env file) gives more precise, visible control over exactly what reaches the container. - Confirm the fix worked with
docker exec <container> printenvdirectly – this shows exactly what the running container actually has, rather than assuming based on what’s in the .env file or compose file alone.
📦 Correct docker-compose.yml
services:
app:
image: myapp:latest
env_file:
- .env # NOW variables actually reach the container
.env being present in the folder was never a guarantee it reaches the container — Compose reads it for its own substitution by default, and getting those values INSIDE the container is a separate, explicit step.




