Docker Environment Variables
Environment variables in Docker allow you to configure applications dynamically without changing the code. They are widely used for storing configuration such as database credentials, API keys, and environment settings.
Why Use Environment Variables?
- Keep sensitive data like passwords outside the code.
- Easily change configuration without rebuilding images.
- Support multiple environments (development, staging, production).
Set Environment Variables Using docker run
docker run -d
--name my-app
-e APP_ENV=production
-e DB_HOST=localhost
-e DB_USER=root
nginx
Using .env File
Create a .env file:
APP_ENV=production
DB_HOST=mysql
DB_USER=root
DB_PASSWORD=secret
Run container with env file:
docker run --env-file .env nginx
Environment Variables in Dockerfile
FROM ubuntu:22.04
ENV APP_NAME=OnlineLearner
ENV APP_ENV=production
CMD ["bash"]
Environment Variables in Docker Compose
version: "3.9"
services:
app:
image: my-app
environment:
APP_ENV: production
DB_HOST: mysql
DB_USER: root
DB_PASSWORD: secret
Access Environment Variables in App
Example in PHP:
$env = getenv("APP_ENV");
echo $env;
Best Practices
- Do not store sensitive data directly in Dockerfile.
- Use
.envfiles or secret managers. - Keep environment-specific configs separate.
Summary
- Environment variables help configure apps dynamically.
- Use
-eflag,.envfiles, or Docker Compose. - Best for managing secrets and environment-based configs.
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
