JIYIK CN >

Current Location:Home > Learning > OPERATING SYSTEM > Docker >

Setting environment variables in Docker

Author:JIYIK Last Updated:2025/03/24 Views:

Environment variables are used to add additional configuration or metadata to aid in the development of an application, and can exist in different forms.

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

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


Create a new project

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

Make sure you have the Node runtime environment installed so that the Node interpreter and package manager section can be automatically added from your 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 called index.js in the docker-env-variables folder 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 simulate an application that returns an array of products in an e-commerce environment. We will use this application to test the examples covered in this tutorial.


Create a Dockerfile

Create a file called Dockerfile in the folder docker-env-variables. Dockerfile is a file that helps us define custom image configurations.

We can use two methods to set environment variables: ARG directive and ENV directive.

The difference between these two instructions is that the environment variables set with the ARG instruction cannot be accessed by the running container, as they are only available when the image is built. The following sections show how to use these instructions to achieve our goals.


Use the ARG command to set environment variables

Copy and paste the following instructions into 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 used alpine, which extracts a lightweight version of Node.js.

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

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

In our example, we provided an optional variable called APP_NAME and a required variable called APP_VERSION.

请注意, these variables are only available when building the image. This will be verified in the next section.

Create an image

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

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

This command executes our Dockerfile sequentially, and we can view the execution of each step as follows.

 => [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 . .

While building the image, we can provide empty environment variable values ​​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 .

Running the container

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

~/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, which we can access on our browser at localhost:3000 (http://localhost:3000/). However, our goal is to check if we can access the environment variables set using the ARG directive.

To check this, use the following command 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 following command. Note that the two variables we set using the ARG directive 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

Use the ENV directive to set environment variables

Comment out the Docker instructions in the previous Dockerfile and copy and paste the following instructions into the commented file.

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 before, the only change we made was replacing the ARG instruction with an ENV instruction.

ENV sets environment variables that the Docker builder can use to create images. Environment variables take the form of key-value pairs.

请注意, these variables are not optional and each value declared must have a value comparable to the previous directive that allowed optional variables.

Since the previous example showed how to create and run a container from it, the same method is used in this example to achieve the same purpose. Using 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

Dynamically setting environment variables

When building an image on the command line, we can use the ARG directive to dynamically assign values ​​to variables defined with the ENV directive.

To see this in action, comment out the previous instructions in the Dockerfile 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

请注意, we added an ARG directive with a variable named HOST_MACHINE, which was dynamically assigned to the ENV directive 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 be assigned to the DEV_ENV variable, or we can assign a value to HOST_MACHINE on the command line using the --build-arg command and we will get the same result.


Summarize

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

The key point to note from here is that environment variables set using the ARG instruction are not accessible from a running container.

Previous: None

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

在 Linux 中托管 Docker Internal

Publish Date:2023/04/18 Views:221 Category:Docker

Docker 允许开发人员通过将应用程序包装在称为容器的标准化单元中来高效地构建、测试和部署应用程序。 在使用 Docker 容器时,您可能会遇到需要将容器与主机连接的场景。

在 Docker 中设置工作目录

Publish Date:2023/04/18 Views:234 Category:Docker

在 Docker 中,我们可以通过编辑 Dockerfile 并添加密钥 WORKDIR 来设置我们的工作目录。本文将讨论在 Docker 中更改我们当前和默认的工作目录。

在 Docker 容器中公开多个端口

Publish Date:2023/04/18 Views:466 Category:Docker

Docker 容器使用端口来实现万维网上不同设备之间的通信。 在本篇文章中,我们将学习如何使用 Nginx 应用程序在 Docker 容器中公开多个端口。

将用户添加到 Docker 容器

Publish Date:2023/04/18 Views:206 Category:Docker

在本文中,我们将学习如何通过实现返回产品数组的 Express 应用程序将用户添加到 Docker 容器。

使用 Docker 网络主机命令

Publish Date:2023/04/18 Views:143 Category:Docker

在本文中,我们将学习如何使用 --network 命令将容器添加到主机网络。 如果我们不使用此命令指定网络,我们还将了解如何将容器添加到默认网络。

清除 Docker 容器日志

Publish Date:2023/04/18 Views:363 Category:Docker

本文介绍了我们可以用来清除 docker 容器中日志的不同方法。日志是应用程序在特定事件或状态发生时记录的信息,它们帮助我们监控应用程序并采取必要的措施。

Docker 中的守护进程日志位置

Publish Date:2023/04/18 Views:319 Category:Docker

本文将讨论守护进程事件以及我们通常可以在哪里找到每个操作系统 (OS) 的守护进程日志。

Dockerfile 中 COPY 和 ADD 命令的区别

Publish Date:2023/04/18 Views:196 Category:Docker

在 Dockerfile 中,我们可以使用 COPY 或 ADD 命令复制这些文件。 这些命令在功能上是相同的; 但是,存在一些差异。本文介绍了 Dockerfile 中 COPY 和 ADD 命令之间的区别。

Docker 中的 --rm 标志

Publish Date:2023/04/18 Views:172 Category:Docker

本文介绍如何在 docker 中使用 --rm 命令。 此外,它还提供了使用命令的优势。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial