迹忆客 EN >

当前位置:主页 > 学无止境 > 操作系统 > Docker >

在 Docker 中创建环境变量文件

作者:迹忆客 最近更新:2023/04/17 浏览次数:

环境变量以键值对的形式提供给应用程序。 我们可以将这些变量视为提供信息以配置或运行应用程序的元数据。

例如,在开发与 Twilio 或 Vonage 等通信服务集成的应用程序时,您必须提供 API 密钥才能使通信服务正常工作。

这些 API 密钥可以作为环境变量提供,应用程序将从 .env 文件中读取密钥的值。

在本文中,我们将学习在 docker 中创建环境变量文件的不同方法。


创建 Nginx 项目

打开 WebStorm IDE 并选择文件>新建>项目。 然后,选择 Empty project 并将项目名称更改为 dockerfile-env-file 或输入任何首选名称。

在当前文件夹下创建一个 index.html 文件,将这段代码复制粘贴到文件中。

<!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>

在这个文件中,我们使用 Bootstrap 5 创建了一个网页,该网页显示了一个包含两个输入字段、一个复选框和一个按钮的表单。 当我们运行一个容器时,就会显示这个网页。


定义一个 Nginx 镜像

在当前文件夹下创建一个名为 Dockerfile 的文件,并将以下说明复制并粘贴到该文件中。

FROM nginx:1.22.0-alpine
COPY . /usr/share/nginx/html
  1. FROM - 按照此命令的说明创建自定义图像。 请注意,这必须是 Dockerfile 中的第一条指令。
  2. COPY - 将主机当前目录中的所有文件和文件夹复制到图像文件系统。 使用 Nginx 镜像时,必须将文件和目录复制到:/usr/share/nginx/html。

创建环境变量文件

在当前文件夹下创建一个名为env-file.list的文件,将以下键值对复制粘贴到文件中。

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

我们将使用此文件将环境变量加载到正在运行的容器中。

请注意 ,文件的内容应使用语法 <variable>=value 将变量设置为分配的值或从本地环境读取值。

使用 Dockerfile 运行容器时,我们可以使用任何文件扩展名,只要内容符合语法即可。 正如您所注意到的,此文件使用 .list 扩展名。


构建镜像

要使用上面定义的 Dockerfile 构建 Nginx 镜像,请在您的计算机上打开一个新的终端窗口并使用以下命令构建映像。

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

此命令按顺序执行 Dockerfile 以构建带有标签 env-image:latest 的图像。 从终端窗口可以看到这个过程,如下。

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

使用 docker run 运行 Nginx 容器

在同一窗口中,使用以下命令运行名为 env-container 的容器。

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

输出:

62fdc85504a2632e5d96aacec4c66c3087a6c1254afadf41bf629b474ceac90c

请注意 ,此命令使用标志 --env-fileenv-file.list 的内容加载到容器中。

该标志的值是环境变量文件的位置。 在我们的例子中,文件位于当前文件夹中; 因此,我们传递了值 ./env-file.list。

要验证文件中的环境变量是否已加载到容器中,请使用以下命令为容器打开交互式 shell。

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

输出:

/ #

在新的 shell 终端上,使用以下命令打印此容器的所有环境变量。

/ # printenv

输出:

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=/

请注意 ,我们在 env-file.list 中添加的环境变量已加载到容器中。 这些变量包括 DATE、DESC、VERSION 和 FOO。


使用 docker-compose 设置一个 .env 文件

在上一节中,我们学习了使用 docker run 命令在 docker 中设置 .env 文件的第一种方法。 在本节中,我们将学习如何使用 docker-compose 设置 .env 文件。

我们必须做的第一件事是将 env-file.list 的扩展名更改为 env-file.env。 Docker 需要一个扩展名为 .env 的文件。 请注意,这是环境变量的默认扩展名。

更改文件扩展名后,在当前文件夹下创建一个名为 compose.yml 的文件,并将以下说明复制并粘贴到该文件中。

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

使用 docker-compose 运行 Nginx 容器

打开一个新的终端窗口并使用以下命令使用 docker-compose 运行 Nginx 容器。

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

输出:

[+] 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

注意,由于我们已经在docker compose.yaml中指定了env_file,所以运行容器时不需要再指定command。

此命令将使用 docker-compose 文件运行容器,并自动使用当前目录中的 env-file.env 文件加载容器中的变量。

要验证 .env 文件中的变量是否已加载到容器中,请使用以下命令从容器中执行交互式 shell。

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

输出:

/ #

在新的 shell 终端上,使用以下命令打印新容器中的所有环境变量。

/ # printenv

输出:

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=/

我们可以从输出中看到,我们在 .env 文件中添加的所有变量都已成功加载到容器中。 这些变量包括 DATE、DESC、VERSION 和 FOO。


总结

在本文中,我们学习了如何使用环境变量文件设置环境变量。 在第一种方法中,我们使用标志 --env-filedocker run 命令将变量加载到容器中。 在第二种方法中,我们在 compose.yaml 文件中添加了 env_file 指令,自动将文件加载到容器中。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Solution to incorrect access log time when deploying Nginx in Docker

发布时间:2025/03/26 浏览次数:165 分类: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

发布时间:2025/03/26 浏览次数:131 分类: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

发布时间:2025/03/26 浏览次数:107 分类: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

发布时间:2025/03/26 浏览次数:97 分类: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

发布时间:2025/03/26 浏览次数:124 分类: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

发布时间:2025/03/26 浏览次数:202 分类: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

发布时间:2025/03/26 浏览次数:87 分类: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

发布时间:2025/03/26 浏览次数:140 分类: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

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便