Docker Environment Variables & Configuration
Complete guide to injecting environment variables into Docker containers using CLI flags, env files, Docker Compose, and Dockerfile defaults.
Environment variables configure applications across development, staging, and production without rebuilding Docker images.
1. Setting Variables via CLI (-e)
# Pass single variables
docker run -d -e NODE_ENV=production -e PORT=8080 -p 8080:8080 myapp
# Pass variable from host environment (without explicit value)
export API_KEY="secret-123"
docker run -d -e API_KEY myapp2. Using Environment Files (--env-file)
Store configuration in .env files:
# .env.production
NODE_ENV=production
DATABASE_URL=postgresql://user:pass@db:5432/production
REDIS_HOST=redis
LOG_LEVEL=infoRun with --env-file:
docker run -d --env-file .env.production -p 3000:3000 myapp[!CAUTION] Never commit
.envfiles containing production credentials or API keys to version control. Add.env*to your.gitignoreand.dockerignore.
3. Setting Defaults in Dockerfile (ENV)
FROM node:22-alpine
ENV NODE_ENV=production \
PORT=3000
WORKDIR /app
COPY . .
EXPOSE $PORT
CMD ["node", "server.js"]ENV values persist in both the image and the running container unless overridden at runtime with -e or --env-file.
Inspecting Container Environment
# Print all environment variables inside a running container
docker exec <container_name> env
# Inspect via docker inspect JSON output
docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' <container_name>Related Topics
Docker Networks & Service Discovery
Complete guide to Docker networking drivers (bridge, host, overlay, macvlan, none), custom user-defined networks, and DNS-based container service discovery.
Docker Container Logs & Logging Drivers
Complete guide to docker logs, streaming logs, log rotation, timestamps, and configuring JSON-file, Syslog, and journald logging drivers.