Advertisement
Intermediate Node.js, Docker & Deployment

What is a .env file, and how does it interact with a Dockerized Node.js application's configuration?

Short answer

A .env file stores key-value environment variables for local use, typically loaded via a package like dotenv -- but inside a Docker container, environment variables are usually better supplied via the 'environment' section of docker-compose.yml or '--env-file' at run time…

Save Node.js mock interview
Advertisement
AModel answer
A .env file stores key-value environment variables for local use, typically loaded via a package like dotenv -- but inside a Docker container, environment variables are usually better supplied via the 'environment' section of docker-compose.yml or '--env-file' at run time, rather than baking a .env file into the image itself, since baking it in would embed potentially sensitive or environment-specific values directly into a shareable image layer.
# docker-compose.yml
services:
  app:
    build: .
    env_file: .env.production

# Or at build/run time
docker run --env-file .env.production myapp
Real-world example
A team removes their .env file from the Docker build context entirely (via .dockerignore) and instead injects environment-specific values at container-run time via docker-compose's env_file option, ensuring the same built image can be safely reused across different environments with different secrets.
Likely follow-ups
  • Why is baking a .env file directly into a Docker image considered a security anti-pattern?
  • How does this approach interact with a proper secrets manager for genuinely sensitive values in production?
Related topics