JIYIK CN >

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

Creating an environment variable file in Docker

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

Environment variables are provided to applications in the form of key-value pairs. We can think of these variables as metadata that provides information to configure or run an application.

For example, when developing an application that integrates with a communications service such as Twilio or Vonage, you must provide an API key in order for the communications service to work properly.

These API keys can be provided as environment variables and the application will read the value of the key from the .env file.

In this article, we will learn different ways to create environment variables file in docker.


Create Nginx project

Open WebStorm IDE and select File > New > Project. Then, select Empty project and change the project name to dockerfile-env-file or enter any preferred name.

Create an index.html file in the current folder and copy and paste this code into the file.

<!doctype html>
<html lang="en">
<head>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
          crossorigin="anonymous">

</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
            <form class="mt-5">
                <div class="mb-3">
                    <label for="exampleInputEmail1" class="form-label">Email address</label>
                    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
                    <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
                </div>
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">Password</label>
                    <input type="password" class="form-control" id="exampleInputPassword1">
                </div>
                <div class="mb-3 form-check">
                    <input type="checkbox" class="form-check-input" id="exampleCheck1">
                    <label class="form-check-label" for="exampleCheck1">Check me out</label>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
        <div class="col-md-3">

        </div>

    </div>

</div>


</body>
</html>

In this file, we have created a web page using Bootstrap 5 that displays a form with two input fields, a checkbox, and a button. This web page is displayed when we run a container.


Define an Nginx image

Create a file called Dockerfile in your current folder and copy and paste the following instructions into it.

FROM nginx:1.22.0-alpine
COPY . /usr/share/nginx/html
  1. FROM - Follow the instructions of this command to create a custom image. Note that this must be the first instruction in your Dockerfile.
  2. COPY - Copies all files and folders in the host's current directory to the image file system. When using the Nginx image, the files and directories must be copied to: /usr/share/nginx/html.

Create an environment variable file

Create a file named env-file.list in the current folder and copy and paste the following key-value pairs into the file.

VERSION=1.0.0
FOO=bar
DESC=This is an Nginx service
DATE=12/11/2022

We will use this file to load environment variables into the running container.

请注意, the contents of the file should use the syntax <variable>=valueto set variables to assigned values ​​or read values ​​from the local environment.

When running a container using a Dockerfile, we can use any file extension as long as the content complies with the syntax. As you noticed, this file uses the .list extension.


Build the image

To build the Nginx image using the Dockerfile defined above, open a new terminal window on your computer and build the image using the following command.

~/WebstormProjects/dockerfile-env-file$ docker build --tag env-image:latest .

This command executes the Dockerfile in sequence to build an image with the tag env-image:latest. You can see this process from the terminal window, as shown below.

 => CACHED [1/2] FROM docker.io/library/nginx:1.22.0-alpine@sha256:addd3bf05ec3c69ef3e8f0021ce1ca98e0eb21117b97ab8b64127e3ff6e444ec                                              0.0s
 => [internal] load build context                                                                                                                                                0.3s
 => => transferring context: 2.45kB                                                                                                                                              0.0s
 => [2/2] COPY . /usr/share/nginx/html                                                                                                                                           0.8s
 => exporting to image                                                                                                                                                           1.0s
 => => exporting layers                                                                                                                                                          0.7s
 => => writing image sha256:de1d72539dd9f36eea4a73d47c07d5aa27bb5f693104c00d9d55a52fba4c26a6                                                                                     0.1s
 => => naming to docker.io/library/env-image:latest

Run the Nginx container using docker run

In the same window, run the container named env-container using the following command.

~/WebstormProjects/dockerfile-env-file$ docker run --name env-container -d -p 80:80 --env-file ./env-file.list env-image:latest

Output:

62fdc85504a2632e5d96aacec4c66c3087a6c1254afadf41bf629b474ceac90c

请注意This command uses the flag --env-file to load the contents of env-file.list into the container.

The value of this flag is the location of the environment variables file. In our case, the file is located in the current folder; therefore, we passed the value ./env-file.list.

To verify that the environment variables in the file have been loaded into the container, use the following command to open an interactive shell for the container.

~/WebstormProjects/dockerfile-env-file$ docker exec -it env-container /bin/sh

Output:

/ #

In a new shell terminal, use the following command to print all the environment variables for this container.

/ # printenv

Output:

HOSTNAME=62fdc85504a2
SHLVL=1
HOME=/root
PKG_RELEASE=1
DATE=12/11/2022
DESC=This is an Nginx service
VERSION=1.0.0
TERM=xterm
NGINX_VERSION=1.22.0
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
FOO=bar
NJS_VERSION=0.7.6
PWD=/

请注意, the environment variables we added in env-file.list have been loaded into the container. These variables include DATE, DESC, VERSION, and FOO.


Setting up a .env file using docker-compose

In the previous section, we learned the first method to set up .env file in docker using docker run command. In this section, we will learn how to set up .env file using docker-compose.

The first thing we must do is change the extension of env-file.list to env-file.env. Docker requires a file with the extension .env. Note that this is the default extension for environment variables.

After changing the file extension, create a file called compose.yml in the current folder and copy and paste the following instructions into the file.

services:
  nginx-app:
    restart: on-failure
    build: ./
    hostname: nginx-app-service
    env_file:
      - ./env-file.env
    ports:
      - '80:80'

Run the Nginx container using docker-compose

Open a new terminal window and use the following command to run the Nginx container using docker-compose.

~/WebstormProjects/dockerfile-env-file$ docker compose up -d

Output:

[+] Building 12.4s (8/8) FINISHED
 => [internal] load build definition from Dockerfile                                 0.2s
 => => transferring dockerfile: 31B                                                  0.0s
 => [internal] load .dockerignore                                                    0.2s
 => => transferring context: 2B                                                      0.0s
 => [internal] load metadata for docker.io/library/nginx:1.22.0-alpine               9.6s
 => [auth] library/nginx:pull token for registry-1.docker.io                         0.0s
 => [internal] load build context                                                    0.2s
 => => transferring context: 476B                                                    0.0s
 => CACHED [1/2] FROM docker.io/library/nginx:1.22.0-alpine@sha256:addd3bf05ec3c69e  0.0s
 => [2/2] COPY . /usr/share/nginx/html                                               1.1s
 => exporting to image                                                               1.0s
 => => exporting layers                                                              0.7s
 => => writing image sha256:e4bd638d4c0b0e75d3e621a3be6526bfe7ed4543a91e68e4829e5a7  0.1s
 => => naming to docker.io/library/dockerfile-env-file_nginx-app                     0.1s

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
[+] Running 2/2
 ⠿ Network dockerfile-env-file_default        Created                                0.2s
 ⠿ Container dockerfile-env-file-nginx-app-1  Started                                2.9s

Note that since we have already specified the env_file in the docker-compose.yaml, we do not need to specify the command when running the container.

This command will run the container using the docker-compose file and automatically use the env-file.env file in the current directory to load the variables in the container.

To verify that the variables in the .env file have been loaded into the container, execute an interactive shell from within the container using the following command.

~/WebstormProjects/dockerfile-env-file$ docker exec -it dockerfile-env-file-nginx-app-1 /bin/sh

Output:

/ #

In a new shell terminal, use the following command to print all environment variables in the new container.

/ # printenv

Output:

HOSTNAME=nginx-app-service
SHLVL=1
HOME=/root
PKG_RELEASE=1
DATE=12/11/2022
DESC=This is an Nginx service
VERSION=1.0.0
TERM=xterm
NGINX_VERSION=1.22.0
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
FOO=bar
NJS_VERSION=0.7.6
PWD=/

We can see from the output that all the variables we added in the .env file have been successfully loaded into the container. These variables include DATE, DESC, VERSION, and FOO.


Summarize

In this article, we learned how to set environment variables using environment variable files. In the first method, we used the flag --env-file and docker runthe command to load the variables into the container. In the second method, we added the env_file directive in the compose.yaml file to automatically load the file into the 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.

Article URL:

Related Articles

Copy files from host to Docker container

Publish Date:2025/03/25 Views:126 Category:Docker

This article will discuss and demonstrate methods we can use to transfer files from the host to a running container in Docker. docker cp Copy the file from the host to the Docker container using docker cp The command is one of the simplest

Get the IP address of the Docker container

Publish Date:2025/03/25 Views:102 Category:Docker

This article demonstrates how to get the IP address of a Docker container. Connect to the Bridge network and get the IP address of the Docker container One of the big reasons why docker containers are so convenient is that we can easily con

Uninstalling Docker on macOS

Publish Date:2025/03/25 Views:95 Category:Docker

Recently, we have seen widespread adoption of Docker as the ultimate containerization platform. Because of this, setting up Docker on all platforms has been greatly simplified, including macOS and Windows. However, some users usually face p

Enter the Docker container's shell

Publish Date:2025/03/25 Views:98 Category:Docker

This article will demonstrate how to enter the Docker container shell using multiple methods. Use docker exec to enter the Docker container's shell We need to have a container up and running to use this command. We can check the status of t

Listing containers in Docker

Publish Date:2025/03/25 Views:122 Category:Docker

This article will discuss various commands for listing containers created in our system. This means we should create some containers beforehand for these commands to return values. List all running containers in Docker We will start by list

Mount the host directory into the Docker container

Publish Date:2025/03/25 Views:189 Category:Docker

Docker provides, among other features, tools to work with the host operating system and the container file system. One of these features is the ability to persist data in containers and share data between containers by mounting directories

Docker build command with multiple parameters

Publish Date:2025/03/25 Views:138 Category:Docker

docker build The command allows us to create a Docker image from a Dockerfile. It also allows us to build an image from a context that references a set of files located in a location specified by a PATH or URL. A Dockerfile, on the other ha

The difference between CMD and ENTRYPOINT in Docker

Publish Date:2025/03/25 Views:141 Category:Docker

Docker containers have become the standard when it comes to managing software and dependencies in different environments. When working with real-world applications, you need to create a docker file before building your application container

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial