Beginner LevelDocker & Deployment
How do ENV instructions and .env files manage environment variables in Docker?
❓ Interview Prompt: Explain ENV vs ARG, --env-file injection, and secrets management best practices for Docker container configuration.
Environment variables are the standard mechanism for 12-Factor App configuration in Docker — keeping configuration out of images and into the runtime environment.
ENV (Dockerfile — Baked into Image):
•
Sets variables permanently into the image — visible in all containers spawned from it.
•
Values are baked into the image layer and visible in
docker inspect.•
Never use ENV for secrets — they appear in image history (
docker history).ARG (Dockerfile — Build-time Only):
•
Available only during
docker build, not at runtime.•
Use for build customization (e.g.,
ARG NODE_VERSION=20).--env and --env-file (docker run — Runtime Injection):
•
-e KEY=value injects individual variables at runtime.•
--env-file .env reads a file of KEY=VALUE pairs — preferred for secrets because the file stays on the host, never inside the image.Code Implementation Example
bash
# Dockerfile — safe usage of ENV and ARG
# ARG NODE_VERSION=20
# FROM node:${NODE_VERSION}-alpine
# WORKDIR /app
# ENV NODE_ENV=production
# COPY . .
# CMD ["node", "server.js"]
# ---
# .env file on host (never committed to git)
cat > .env << EOF
DATABASE_URL=postgres://user:secretpass@db:5432/prod
JWT_SECRET=my-jwt-secret-key
REDIS_URL=redis://:redispass@redis:6379
EOF
# Inject at runtime — .env stays on host, never in image
docker run -d \
--env-file .env \
-e PORT=3000 \
--name api \
myapp:latest
# View env vars in running container (for debugging)
docker exec api printenv DATABASE_URL💡Use ENV for non-secret configs, ARG for build variables, and --env-file for runtime secrets.
🎯 Interview Key Takeaway
Never bake secrets into images with ENV. Use --env-file to inject secrets at runtime, keeping them out of image layers and git history.
#Docker#Environment Variables#ENV#Secrets#.env#Beginner
Back to all Docker & Deployment Questions→