Kritim Yantra
Apr 25, 2025
When working with Docker Compose, using environment variables is one of the best ways to make your configuration dynamic, reusable, and secure.
In this blog, you’ll learn:
.env
filesLet’s get started!
Environment variables are key-value pairs used to store configuration settings. They let you define data like:
This helps you avoid hardcoding sensitive or changing values directly into your code or Docker Compose file.
docker-compose.yml
Docker Compose allows you to use environment variables by referencing them with ${}
syntax.
version: '3.9'
services:
web:
image: "nginx:${NGINX_VERSION}"
ports:
- "${APP_PORT}:80"
environment:
- APP_ENV=${APP_ENV}
- API_KEY=${API_KEY}
Here:
NGINX_VERSION
, APP_PORT
, APP_ENV
, and API_KEY
are environment variables..env
file..env
FileDocker Compose automatically looks for a file named .env
in the same directory as your docker-compose.yml
.
.env
ExampleNGINX_VERSION=latest
APP_PORT=8080
APP_ENV=development
API_KEY=12345-abcdef
docker-compose up
Docker Compose will automatically inject the values from .env
.
docker-compose.yml
version: '3.9'
services:
app:
build:
context: .
args:
NODE_ENV: ${NODE_ENV}
environment:
- NODE_ENV=${NODE_ENV}
ports:
- "${APP_PORT}:3000"
volumes:
- .:/app
.env
NODE_ENV=development
APP_PORT=3000
You can also pass environment variables inline when running Docker Compose:
NODE_ENV=production APP_PORT=8080 docker-compose up
These will override what's in your .env
file or system.
env_file
in ComposeIf you want to load variables into a service’s container, use the env_file
property.
services:
app:
image: myapp
env_file:
- ./app.env
app.env
DB_HOST=db
DB_USER=root
DB_PASS=password
📝 This file is loaded into the container’s environment, not the Compose file itself.
Feature | .env file |
env_file |
---|---|---|
Used by | Docker Compose engine | Container at runtime |
Purpose | Replaces variables in docker-compose.yml |
Sets environment inside container |
Syntax | KEY=value |
KEY=value |
Scope | File-wide | Service-specific |
🔒 Keep .env
files out of version control
Use .gitignore
to avoid committing secrets:
.env
*.env
🧹 Use defaults in your Compose file
ports:
- "${APP_PORT:-8000}:80"
🛠️ Use docker-compose config
to debug
Run this to see the final file after variable substitution:
docker-compose config
Feature | Description |
---|---|
${VAR} |
Use environment variables inside Compose |
.env |
File loaded automatically by Compose |
env_file |
Loads variables into container runtime |
CLI variables | Override variables temporarily |
docker-compose config |
Show merged config with variables expanded |
Using environment variables in Docker Compose is a simple but powerful way to:
Try replacing some of your hardcoded values with ${}
variables today — your future self will thank you! 🙌
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google