Contents

Docker Environment Variables

Website Visitors:

Environment Variables

Environment variables in Docker are key-value pairs that can be passed to a Docker container at runtime. They are used to configure the behavior of the application running inside the container without changing the container image itself.

Environment variables can be set in a Dockerfile using the ENV instruction or passed to the container when it is run using the -e flag with the docker run command. These variables can be accessed by the application running inside the container to customize its behavior based on the environment it is running in.

Environment variables are commonly used to store configuration settings such as database connection strings, API keys, and other sensitive information that should not be hard-coded into the container image. By using environment variables, you can keep your containerized applications flexible and portable across different environments.

Overall, environment variables in Docker provide a convenient way to manage configuration settings and sensitive information in a secure and flexible manner.

Example:

Let’s say you have a simple Node.js application that connects to a MongoDB database. Instead of hard-coding the database connection string in your application code, you can use an environment variable to store it.

First, you can define an environment variable in your Dockerfile like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
FROM node:14

ENV MONGO_URI=mongodb://localhost:27017/mydatabase

WORKDIR /app

COPY package.json .
RUN npm install

COPY . .

CMD ["node", "app.js"]

In this example, we are setting the MONGO_URI environment variable to mongodb://localhost:27017/mydatabase.

When you run your container, you can pass a different value for the MONGO_URI environment variable like this:

1
docker run -e MONGO_URI=mongodb://mongo:27017/mydatabase my-node-app

This way, you can easily configure your Node.js application to connect to different MongoDB databases by simply changing the value of the MONGO_URI environment variable when running the container.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.