How to Set Up Environment Variables in Docker Containers

Environment variables are crucial in Docker for configuring containerized applications dynamically. This guide covers multiple methods to set environment variables inside Docker containers.


Step 1: Install Docker

Ensure Docker is installed:

docker --version

If Docker is not installed:

  • Linux (Ubuntu):
sudo apt update
  sudo apt install docker.io -y

Step 2: Create a Sample Web Application

We’ll create a simple Node.js web app that reads environment variables.

(A) Create a Project Directory

mkdir my-web-app && cd my-web-app

(B) Initialize a Node.js Project

npm init -y

(C) Install Dependencies

npm install express dotenv

(D) Create server.js File

touch server.js

(E) Add the Following Code in server.js

require('dotenv').config();
const express = require('express');
const app = express();

const PORT = process.env.PORT || 3000;
const DB_HOST = process.env.DB_HOST || 'localhost';
const DB_USER = process.env.DB_USER || 'root';
const DB_PASS = process.env.DB_PASS || 'password';

app.get('/', (req, res) => {
  res.send(`Connected to DB: ${DB_HOST} with user ${DB_USER}`);
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

✅ This app will display database credentials stored in environment variables.


Step 3: Create a Dockerfile

FROM node:18
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

Step 4: Build and Run the Docker Container (Using -e Flag)

(A) Build the Docker Image

docker build -t my-web-app .

(B) Run the Container with Environment Variables

docker run -d -p 3000:3000 \
  -e DB_HOST=mysql \
  -e DB_USER=admin \
  -e DB_PASS=secret \
  my-web-app

Step 5: Verify the Running Container

docker ps

Step 6: Test the Application

Open your browser and visit:
👉 http://localhost:3000

You should see:

Connected to DB: mysql with user admin

Step 7: Use a .env File (Alternative Method)

(A) Create a .env File

vim .env

(B) Add This Content to .env

DB_HOST=mysql
DB_USER=admin
DB_PASS=secret
PORT=3000

(C) Modify docker-compose.yml to Load the .env File

version: "3.8"
services:
  web:
    image: my-web-app
    build: .
    ports:
      - "3000:3000"
    env_file:
      - .env

(D) Run the App Using Docker Compose

docker-compose up -d

This method automatically loads environment variables from .env.


Step 8: Stopping & Cleaning Up

To stop the running container:

docker stop

To remove all stopped containers:

docker rm $(docker ps -aq)

Final Summary

Method Command
Using -e flag docker run -d -e DB_HOST=mysql -e DB_USER=admin -e DB_PASS=secret my-web-app
Using .env file with Docker Compose docker-compose up -d
Checking Environment Variables Inside Container docker exec -it env