Setting environment variables in Docker
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.
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.
Related Articles
Get the IP address of the Docker container from the host using docker inspect
Publish Date:2025/03/26 Views:103 Category:Docker
-
Docker containers are not just for isolation—they are often used to manage processes that still need to communicate directly with each other. However, to communicate, you usually need to know the IP address of each container, which you ca
Solution to incorrect access log time when deploying Nginx in Docker
Publish Date:2025/03/26 Views:165 Category:Docker
-
In the process of operating the website, I never took the logs too seriously. Although logging was turned on, I never analyzed the logs carefully. Today, when I looked at the logs on a whim, I found that the recorded time was 8 hours less t
Docker deploys nginx php application
Publish Date:2025/03/26 Views:131 Category:Docker
-
I'm learning docker recently. I'm learning by building an nginx+php development environment example. Here I record the build process. First, give a docker-compose.yml deployment configuration file version: '3' services: nginx: container_nam
How to use Docker to image a Node.js web application
Publish Date:2025/03/26 Views:107 Category:Docker
-
Docker is a containerization platform that simplifies the packaging and execution of applications. Containers run as independent processes with their own file systems, but share the kernel of their host machine. Docker has attracted much at
Start a Bash terminal in a new Docker container
Publish Date:2025/03/26 Views:97 Category:Docker
-
Docker containers are a standard unit for packaging all the dependencies of an application, allowing us to easily run them in any environment. Containers have become very popular recently, and most developers now rely heavily on containers
Passing environment variables to containers in Docker
Publish Date:2025/03/26 Views:125 Category:Docker
-
This article will introduce how to pass environment variables to containers in Docker. Passing environment variables to containers in Docker using the -e and tags -env We will first see how to create environment variables and pass them to t
Install Docker using Homebrew
Publish Date:2025/03/26 Views:202 Category:Docker
-
There is no doubt that Docker containers have revolutionized the way we develop and deploy applications. They provide developers with the ability to package applications and dependencies in an isolated environment. Recently, we've seen wide
Enforce clean build of images in Docker
Publish Date:2025/03/26 Views:88 Category:Docker
-
This article discusses and demonstrates how to enforce clean builds of images in Docker. Building images in Docker We will use a simple Flask application to demonstrate this concept. my-app Create a app.py simple application named in the ho
Running a Docker instance from a Dockerfile
Publish Date:2025/03/26 Views:140 Category:Docker
-
Docker containers have undoubtedly become the standard unit for managing software and dependencies in different environments. When using real applications, you must create a docker file before building the container image of the application