Docker · Containers in practice
How should you configure containers with environment variables?
Short answer
Pass configuration at runtime with -e or --env-file, and keep the image environment-agnostic. Environment variables are fine for non-secret settings but not for sensitive credentials.
The twelve-factor approach keeps configuration outside the image so one artifact can run in staging and production. ENV in a Dockerfile bakes a value into every container, which is useful for safe defaults but wrong for environment-specific or secret values.
docker run -e NODE_ENV=production -e LOG_LEVEL=info api:1.0.0
docker run --env-file ./prod.env api:1.0.0
docker exec api-1 env | sortGood practice
- Validate required variables at startup and fail fast with a clear message
- Document every variable and provide safe defaults where possible
- Use an env file in Compose for local development
- Keep secrets in a secret manager or mounted file, not in the image or env file
Environment variables are visible to the process and often to anyone who can inspect the container or read its config. They also appear in crash dumps and child processes. That is acceptable for a log level and unacceptable for a database password.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is ENV in the Dockerfile a bad place for environment-specific values?
- 2What is the difference between ARG and ENV?
- 3Why should secrets not be passed as environment variables?
- 4How do you handle a missing required variable?
Say it in the interview
I keep the image environment-agnostic and pass configuration at runtime with -e or an env file. I validate required values at startup so a misconfiguration fails immediately rather than at the first request. Environment variables are fine for log levels and feature flags, but I keep credentials in a secret manager because environment variables are easy to inspect.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.