Advertisement
Intermediate Node.js, Docker & Containerization for Node.js

How do you use environment variables and Docker's --env-file (or docker-compose's environment section) to configure a containerized Node.js application per environment?

Short answer

Rather than baking environment-specific configuration into the image itself, values are injected at container runtime via -e flags, an --env-file, or docker-compose.yml's environment/env_file sections -- keeping the same built image usable unchanged across development, staging…

Save Node.js mock interview
Advertisement
AModel answer
Rather than baking environment-specific configuration into the image itself, values are injected at container runtime via -e flags, an --env-file, or docker-compose.yml's environment/env_file sections -- keeping the same built image usable unchanged across development, staging, and production, with only the externally supplied environment variables differing, consistent with the twelve-factor app methodology.
# docker-compose.yml
services:
  app:
    image: my-app:latest
    env_file: .env.production
    environment:
      - NODE_ENV=production
    ports:
      - '3000:3000'
Real-world example
A team builds a single Docker image tagged with a Git commit SHA and deploys that exact same image to staging and production, differing only in which env_file is supplied at container startup, guaranteeing the artifact tested in staging is byte-for-byte identical to what runs in production.
Likely follow-ups
  • Why is baking environment-specific secrets directly into a Docker image considered a security anti-pattern?
  • How does this approach interact with a secrets manager for genuinely sensitive values rather than plain environment variables?
Related topics