Docker Run with Environment Variables
Last Updated :
08 Jul, 2024
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
What Docker Environmental Variables ?
In a Docker has entered into the developer's working culture today as a forefront system of development, testing, and deployment of applications. Docker is an important feature as it provides the users or developers with the ability to not only monitor and control the environment but to also build t
6 min read
Read Environment Variables with Python dotenv
Environment variables play a crucial role in the configuration and operation of software applications. They provide a mechanism to store configuration settings that can be used by applications to function properly. This separation of configuration from code allows for more secure and flexible softwa
4 min read
How to Pull Environment Variables with Helm Charts
Helm Chart is widely regarded as the package manager for Kubernetes. While it may appear to be just another package manager, it extends a great deal more. Helm makes managing application components easy by grouping those parts into charts, which can then be easily installed and upgraded.What is Helm
4 min read
Environment Variables in Java
In Java, Environment variables are widely used by operating systems to deliver configuration data to applications. Environment variables are key/value pairs with both the key and the value being strings, similar to properties in the Java platform. What are Environment Variables in Java?In Java, Envi
5 min read
How to Load environment variables from .env file using Vite?
The environment variables in the application are managed through .env files in a Vite project, allowing you to configure and access various settings dynamically. By prefixing variables with VITE_, Vite exposes them to your applicationâs runtime environment. This approach facilitates different config
2 min read
Execution of C Program Using Docker Environment
Docker as a platform provides the ability to package, ship, and run an application in an isolated environment called a container. This isolation allows running many containers simultaneously on a given host. Containers are lightweight and contain everything needed to run the application and no need
2 min read
How to add environment variable in MacOS?
While programmers work on different Programming Languages, they use to declare Variables to work on any certain piece of code. The Variables in general terms are used to store some values that can be again accessed in the future. There are some Operating System Variables present that are known as En
3 min read
What is Docker Engine?
Docker Engine is the actual technology behind building, shipping, and running container applications. However, it does its work in a client-server model, which requires using many components and services for such operations. When people refer to "Docker," they are probably referring to either Docker
12 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-va
3 min read
Implementing Canary Releases with Docker
In the world of today in software development, deployment strategies play a very important role in ensuring application stability while rolling out new features. One such strategy for effective changes is the canary release. Docker, being flexible and scalable technology, fits perfectly within the i
6 min read