Main idea
Environment variables are values passed into an app from outside the code.
This page explains how Docker containers receive configurable values like app port, database host, and runtime mode without changing the source code itself.
Environment variables are values passed into an app from outside the code.
They help you change configuration for development, testing, and production without rewriting the application.
Secrets like passwords and API keys should be handled carefully, even when using environment variables.
PORT=3000
DB_HOST=db
DB_USER=root
DB_PASSWORD=secret123
NODE_ENV=development
The same app can use different ports, databases, or runtime modes depending on where it runs, without changing the source code.
docker run -d -p 3000:3000 \
-e PORT=3000 \
-e NODE_ENV=development \
my-app
services:
app:
build: .
environment:
PORT: 3000
DB_HOST: db
NODE_ENV: development
services:
app:
build: .
ports:
- "3000:3000"
environment:
PORT: 3000
DB_HOST: db
NODE_ENV: development
depends_on:
- db
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: rootpass
PORT=3000
DB_HOST=db
DB_USER=root
DB_PASSWORD=secret123
NODE_ENV=development
A `.env` file can keep configuration values in one place, which makes Compose files cleaner and easier to maintain.
services:
app:
build: .
ports:
- "${PORT}:3000"
environment:
PORT: ${PORT}
DB_HOST: ${DB_HOST}
NODE_ENV: ${NODE_ENV}
Here, Compose reads values from the `.env` file and replaces placeholders like ${PORT} before starting the service.
const port = process.env.PORT || 3000;
const dbHost = process.env.DB_HOST;
This is how a Node.js app reads configuration that Docker passes into the container at runtime.
PORT=3000 and DB_HOST=db inside a `.env` file.${PORT}.process.env.PORT.Next page: Lesson 8 combines Dockerfile, Compose, volumes, networks, and configuration in one small real Docker project.