Skip
Arish's avatar

11. Environment Variables


Setting Environment Variables

bash
1# Single variable
2docker run -e DATABASE_URL=postgres://localhost/db nginx
3
4# Multiple variables
5docker run \
6  -e DATABASE_URL=postgres://localhost/db \
7  -e REDIS_URL=redis://localhost \
8  -e SECRET_KEY=abc123 \
9  myapp

Using .env File

bash
1# .env file
2DATABASE_URL=postgres://localhost/db
3REDIS_URL=redis://localhost
4SECRET_KEY=abc123
5
6# Use with --env-file
7docker run --env-file .env myapp

From Host Environment

bash
1# Pass existing variable
2export DATABASE_URL=postgres://localhost/db
3docker run -e DATABASE_URL myapp

View Container Environment

bash
1docker exec mycontainer env
2docker exec mycontainer printenv DATABASE_URL

Security Notes

  • Don't put secrets in Dockerfile
  • Use Docker secrets or vault for sensitive data
  • Use .env files (not committed to git)