Docker Run with Environment Variables
Last Updated :
23 Jul, 2025
Containerization has significantly advanced software development by packaging applications and their dependencies together and containerizing them to ensure consistency across multiple environments. Environment variables are one of the most important features of containerization as they make it possible to manage configuration and behavior.
Imagine you are working on an application that needs to connect to different databases in development, testing, and production environments. Hardcoding these configurations can lead to errors in the codebase. This is where the environment variables come into play, which allows you to change the config without altering the code. Docker will let you pass these variables with ease so that your containerized application will behave exactly the way you want it to across different environments.
What is Docker?
Docker helps to automate the applications’ deployment, scaling, and management. This is achieved by creating containerization using which an application and its dependencies are bundled together in containers and can run on any system that supports Docker.
What are environmental variables?
Environment variables are dynamic values that can affect the way running processes behave on a computer. They are a set of key-value pairs used to configure the operating environment for applications. Database connection strings, API keys, and service endpoints are some of the examples usually stored as environment variables.
Why Use Environment Variables with Docker?
Environment variables with Docker provide a number of value propositions:
- Configuration Management: Switch configurations among different environments easily without touching the code.
- Security: Secrets such as passwords and API keys can be kept separate from the codebase.
- Portability: Containers can be moved across different environments while maintaining consistent behavior.
A Basic Node.js Application Example
To illustrate how to use environment variables with Docker, let's create a basic Node.js application that reads a message from an environment variable and prints it.
Step 1: Set Up the Node.js Application
First, create a directory for your project and initialize a new Node.js application:
mkdir node-docker-env
cd node-docker-env
npm init -y
Next, install the Express framework:
npm install express
Create an index.js file with the following content:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const message = process.env.MESSAGE || 'Hello, World!';
app.get('/', (req, res) => {
res.send(message);
});
app.listen(port, () => {
console.log(`App running on port ${port}`);
});
This simple application reads the PORT and MESSAGE environment variables. If they are not set, it defaults to port 3000 and the message "Hello, World!".
Create a .env file with the following environment variables:
PORT=3000
MESSAGE=Hello from .env file!
Step 2: Create a Dockerfile
A Dockerfile is a script that contains instructions on how to build a Docker image for your application. Create a file named `Dockerfile` in your project directory with the following content:
FROM node
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "node", "index.js" ]
This is how your folder structure would look like:
Step 3: Build the Docker Image
With your Dockerfile ready, you can build your Docker image. Run the following command in your project directory:
docker build -t node-docker-env .
This command builds an image named node-docker-env based on the instructions in the Dockerfile.
Step 4: Run the Docker Container with Environment Variables
There are two ways of passing environment variables into a container:
Method 1: Using -e flag:
Now that you have a Docker image, you can run a container from it. Use the -e flag to pass environment variables to the container:
docker run -p 3000:3000 -e PORT=3000 -e MESSAGE="Hello from docker run command" node-docker-env
In this command:
- -p 3000:3000 maps port 3000 on your host to port 3000 in the container.
- -e PORT=3000 sets the `PORT` environment variable.
- -e MESSAGE="Hello from docker run command" sets the `MESSAGE` environment variable.
Open your browser and navigate to `http://localhost:3000`. You should see the message "Hello from docker run command".
Method 2: Using --env-file flag:
Managing multiple environment variables directly in the command line can become cumbersome. A more convenient approach is to use an environment file. You can use the --env-file flag to pass the environment variables from the .env file to the Docker container:
docker run -p 3000:3000 --env-file .env node-docker-env
Open your browser and navigate to http://localhost:3000. You should see the message "Hello from .env file!".
Defining Environment Variables in Docker Compose
For more complex applications, managing environment variables directly in the docker run command can become cumbersome. Docker Compose simplifies this by allowing you to define environment variables in a docker-compose.yml file.
Create a docker-compose.yml file with the following content:
version: '3.8'
services:
app:
image: node-docker-env
build: .
ports:
- "3000:3000"
environment:
- PORT=3000
- MESSAGE=Hello from Docker Compose
In the above example, we have listed all the environment variables in the YAML file. We can directly use .env file in Docker Compose as well:
version: '3.8'
services:
app:
image: node-docker-env
build: .
ports:
- '3000:3000'
env_file:
- .env
You can now start your application using Docker Compose:
docker-compose up
Best Practices for Managing Environment Variables
- Use a `.env` File: Store environment variables in a `.env` file and reference it in your Docker Compose file. This keeps your configuration organized and secure.
- Avoid Hardcoding Secrets: Never hardcode sensitive information like passwords or API keys in your Dockerfile or source code. Use environment variables instead.
- Separate Configurations: Use different `.env` files for different environments (development, testing, production) to ensure each environment has its specific configuration.
- Document Variables: Maintain a README or documentation listing all environment variables used in your application, their purpose, and possible values.
Conclusion
Using environment variables in Docker is the best way to handle the configuration of applications across various environments in a secure manner. This ensures that your application behaves as expected in both development and deployment scenarios, when following best practices and with tools such as Docker Compose. With the provided Node. With the provided Node.js example, you now have a solid foundation to start integrating environment variables into your own Dockerized applications.
Besides this, environment variables facilitate the application's flexibility, allowing the user to easily move from one development stage to another, without the need for manual intervention. In the first place, this model does not only mitigate configuration errors but also standardize quality management across different configurations in complex, multi-service architectures. With the application of such methods you are more likely to get the outcomes you expect in a more productive, flexible, and safe DevOps pipeline.
Later on in your journey with Docker, you will see more methods and tools that will help you take your deployment strategies to the next level. Environment variables represent simply the basic properties. Docker offers features like managing containers, volumes, networks, and secrets, that will help you to create stable, that is easily programmable, and deployable modules. Embrace the power of containerization and environment variables to unlock the full potential of your development process.
Similar Reads
DevOps Tutorial DevOps is a combination of two words: "Development" and "Operations." Itâs a modern approach where software developers and software operations teams work together throughout the entire software life cycle.The goals of DevOps are:Faster and continuous software releases.Reduces manual errors through a
7 min read
Introduction
What is DevOps ?DevOps is a modern way of working in software development in which the development team (who writes the code and builds the software) and the operations team (which sets up, runs, and manages the software) work together as a single team.Before DevOps, the development and operations teams worked sepa
10 min read
DevOps LifecycleThe DevOps lifecycle is a structured approach that integrates development (Dev) and operations (Ops) teams to streamline software delivery. It focuses on collaboration, automation, and continuous feedback across key phases planning, coding, building, testing, releasing, deploying, operating, and mon
10 min read
The Evolution of DevOps - 3 Major Trends for FutureDevOps is a software engineering culture and practice that aims to unify software development and operations. It is an approach to software development that emphasizes collaboration, communication, and integration between software developers and IT operations. DevOps has come a long way since its in
7 min read
Version Control
Continuous Integration (CI) & Continuous Deployment (CD)
Containerization
Orchestration
Infrastructure as Code (IaC)
Monitoring and Logging
Microsoft Teams vs Slack Both Microsoft Teams and Slack are the communication channels used by organizations to communicate with their employees. Microsoft Teams was developed in 2017 whereas Slack was created in 2013. Microsoft Teams is mainly used in large organizations and is integrated with Office 365 enhancing the feat
4 min read
Security in DevOps