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

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

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial