How to Set Environment Variables in Docker

David Mbochi Njonge Feb 02, 2024
  1. Create a New Project
  2. Create a Dockerfile
  3. Set Environment Variables Using the ARG Instruction
  4. Set Environment Variables Using the ENV Instruction
  5. Set Environment Variables Dynamically
  6. Conclusion
How to Set Environment Variables in Docker

Environment variables are used to add extra configurations or metadata to help develop an application and can exist in different forms.

For example, when developing a Java application, we usually set an environment variable that points to the Java development kit location to ensure that we can compile and run our applications.

Similarly, we can set environment variables for our containers when using Docker to develop our application. In this tutorial, we will learn how to set ENV variables and how to access the variables from a running container where necessary.

Create a New Project

Open WebStorm IDEA and select File > New > Project. On the window that opens, select Node.js and change the project name from untitled to docker-env-variables or use any name preferred.

Ensure you have installed the Node runtime environment so that the Node interpreter and Package manager sections can be added automatically from the computer. Finally, press the button labeled Create to generate the project.

Since our application uses expressjs, use the following command to install expressjs into our application.

~/WebstormProjects/docker-env-variables$ npm install express

After installing expressjs, create a file named index.js in the folder docker-env-variables and copy and paste the following code into the file.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    res.json(
        [{
            name: 'Lenovo Legion 5 pro',
            type: 'electronic',
            price: 1500
        },
            {
                name: 'Xiaomi pro 14',
                type: 'electronic',
                price: 1300
            },
        ])
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

In this file, we have simulated an application that returns an array of products in an e-commerce environment, and we will use this application to test the examples covered in this tutorial.

Create a Dockerfile

Create a file named Dockerfile in the folder docker-env-variables. A Dockerfile is a file that helps us to define configurations for our custom image.

There are two approaches we can use to set environment variables: the ARG instruction and the ENV instruction.

The difference between these two instructions is that a running container cannot access the environment variables set using the ARG instruction, as they are only available when building the image. The following sections show how to use these instructions to achieve our objective.

Set Environment Variables Using the ARG Instruction

Copy and paste the following instructions in the file named Dockerfile we created in the previous section.

FROM node:16.17.0-alpine
ARG APP_NAME
ARG APP_VERSION=1.0.0
RUN echo "build an image of ${APP_NAME} version ${APP_VERSION}"
WORKDIR /com/ecommerce
ADD package*.json ./
RUN npm install
COPY . .
CMD node index.js

The FROM instruction sets our base image on which to create our custom image. In our case, we have used alpine, which pulls the lightweight version of Node.

The ARG defines variables that the Docker builder can use to build an image. The variables provided using this instruction can be required or optional.

The Docker documentation provides a reference where we can read the other instructions.

In our case, we have provided an optional variable named APP_NAME and a required variable named APP_VERSION.

Note that these variables will only be available when building an image. The next section verifies this.

Create an Image

Use the command below to build an image with the tag docker-env:latest.

~/WebstormProjects/docker-env-variables$ docker build --tag docker-env:latest .

This command executes our Dockerfile sequentially, and we can view each step being executed, as shown below.

 => [1/6] FROM docker.io/library/node:16.17.0-alpine@sha256:2c405ed42fc0fd6aacbe5730042640450e5ec030bada7617beac88f742b6  0.0s
 => CACHED [2/6] RUN echo "build an image of ${APP_NAME} version 1.0.0"                                                   0.0s
 => [3/6] WORKDIR /com/ecommerce                                                                                          0.6s
 => [4/6] ADD package*.json ./                                                                                            0.8s
 => [5/6] RUN npm install                                                                                                 6.7s
 => [6/6] COPY . .

When building an image, we can provide the values of empty environment variables or override the default environment values using the --build-arg command, as shown below.

~/WebstormProjects/docker-env-variables$ docker build --build-arg APP_NAME=ecommerce-app --tag docker-env:latest .

Run a Container

Use the command below to run a container named docker-env-prod that exposes port 3000 on the host.

~/WebstormProjects/docker-env-variables$ docker run --name docker-env-prod -d -p 3000:3000 docker-env:latest

This command runs an instance of our application, and we can access it on the browser at localhost:3000 (http://localhost:3000/). However, we aim to check if we can access the environment variables set using the ARG instruction.

To check this, use the command below to access our container file system in interactive mode.

~/WebstormProjects/docker-env-variables$ docker exec -it docker-env-prod /bin/sh

Output:

/com/ecommerce #

To display the current environment variables, use the command below and note that the two variables we set using the ARG instruction are not displayed.

/com/ecommerce # printenv

Output:

NODE_VERSION=16.17.0
HOSTNAME=1bbf5ec4141e
YARN_VERSION=1.22.19
SHLVL=1
HOME=/root
TERM=xterm
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/com/ecommerce

Set Environment Variables Using the ENV Instruction

Make the previous Docker instructions in the Dockerfile as comments and copy and paste the following instructions into the file after the comment.

FROM node:16.17.0-alpine
ENV APP_NAME=ecommerce-app
ENV APP_VERSION=1.0.0
RUN echo "build an image of ${APP_NAME} version ${APP_VERSION}"
WORKDIR /com/ecommerce
ADD package*.json ./
RUN npm install
COPY . .
CMD node index.js

The instructions in this Dockerfile are the same as the previous one, and the only change we have made is replacing the ARG instruction with the ENV instruction.

The ENV sets environment variables that the Docker builder can use to create an image. The environment variables are in the form of key-value pairs.

Note that these variables are not optional, and each value declared must have a value compared to the previous instruction that allows optional variables.

Since the previous example illustrated how to create and run a container from it, use the same approaches to achieve the same in this example. With the ENV instruction, we can access our two environment variables, APP_NAME and APP_VERSION, as shown below.

NODE_VERSION=16.17.0
HOSTNAME=0cca1ee1340d
YARN_VERSION=1.22.19
SHLVL=1
HOME=/root
APP_NAME=ecommerce-app
TERM=xterm
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/com/ecommerce
APP_VERSION=1.0.0

Set Environment Variables Dynamically

When building images on the command line, we can use the ARG instruction to dynamically assign values to variables defined using the ENV instruction.

To view this in action, make the previous instructions in the Dockerfile as comments and copy and paste the following instructions into the file.

FROM node:16.17.0-alpine
ARG HOST_MACHINE
ENV APP_NAME=ecommerce-app
ENV APP_VERSION=1.0.0
ENV DEV_ENV=$HOST_MACHINE
RUN echo "build an image of ${APP_NAME} version ${APP_VERSION}"
WORKDIR /com/ecommerce
ADD package*.json ./
RUN npm install
COPY . .
CMD node index.js

Note that we have added an ARG instruction with a variable named HOST_MACHINE, which is dynamically assigned to an ENV instruction with the variable name DEV_ENV by referencing the variable name $HOST_MACHINE.

We can create a default value for the variable name HOST_MACHINE, which will also get allocated to the DEV_ENV variable, or use the --build-arg command on the command line to assign HOST_MACHINE a value and we will get the same results.

Conclusion

In this tutorial, we have learned how to set environment variables and how to access these variables from a running container. We have learned how to use the ARG instruction, the ENV instruction, and how to dynamically set environment variables.

The main point to note from this is that the environment variables set using the ARG instruction cannot be accessed from a running container.

David Mbochi Njonge avatar David Mbochi Njonge avatar

David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.

LinkedIn GitHub

Related Article - Docker Environment Variable