【问题标题】:Docker environment variables in multi-stage builds多阶段构建中的 Docker 环境变量
【发布时间】:2018-04-20 06:40:59
【问题描述】:

鉴于此.env 文件:

TEST=33333

鉴于此docker-compose.yml 文件:

  service_name:
    image: test
    env_file: .env
    environment:
      TEST: 22222

鉴于此Dockerfile 文件:

FROM an_image AS builder

FROM another_image
ENV TEST 11111

CMD ["/bin/echo $TEST"]

每当我在容器中构建和运行此映像时,它都会打印11111。

如果我从 Dockerfile 中删除 ENV 11111 行,我的 TEST 环境变量为空...

父图像是否接收环境变量而不是子图像?

谢谢!

编辑:

  1. 尝试ENV TEST ${TEST} 无效($TEST 为空)
  2. 删除 ENV TEST 无效($TEST 为空)

【问题讨论】:

    标签: docker environment-variables docker-compose dockerfile


    【解决方案1】:

    问题不在于多阶段。

    这是关于 Dockerfile ARG 和 docker-compose YAML build args (“构建参数”)之间的差异;和 Dockerfile ENV & docker-compose YAML environment/.env.

    The docs were updated (more recently than the original post), and it is fairly clear now:

    args

    添加构建参数,它们是只能在构建过程中访问的环境变量。

    来自the docker-compose docs 的示例

    从简单的开始,只展示Dockerfile 和 YAML 之间的交互:

    ARG buildno
    ARG gitcommithash
    
    RUN echo "Build number: $buildno"
    RUN echo "Based on commit: $gitcommithash"
    
    build:
      context: .
      args:
        buildno: 1
        gitcommithash: cdc3b19
    
    build:
      context: .
      args:
        - buildno=1
        - gitcommithash=cdc3b19
    

    将其与问题联系起来的示例:

    见the other answer in this thread.


    文档和加深您的理解

    一次学习一层抽象

    我建议从 Dockerfile 抽象级别开始,向上。确保在添加下一层抽象之前了解每一层。

    1. Dockerfile(然后使用 Dockerfile 中正在运行的容器...使用默认 ENV,然后使用 --env,然后使用 ARG 和 --build-arg)

    2. 然后添加 docker-compose 详细信息,并使用它们。

    3. 然后循环回到 Dockerfiles 并了解多阶段构建。

    Dockerfile

    一篇有用的博文——重点介绍 Dockerfile,但在所有情况下,最好先单独了解 Dockerfile,然后再在其上添加额外的抽象层,例如 docker-compose YAML。

    https://vsupalov.com/docker-arg-env-variable-guide/

    码头工人撰写

    然后是 docker-compose 官方文档:

    多阶段 Dockerfiles

    【讨论】:

      【解决方案2】:

      所以这不是一个多阶段的问题。

      似乎ENV 变量仅在运行容器时使用(docker-compose up)。不在构建时 (docker-compose build)。所以你必须使用arguments:

      .env:

      TEST=11111
      

      docker-compose.yaml:

      version: '3'
      services:
        test:
          build:
            context: .
            args:
              TEST: ${TEST}
      

      Dockerfile:

      FROM nginx:alpine
      ARG TEST
      ENV TEST ${TEST}
      CMD ["sh", "-c", "echo $TEST"]
      

      测试命令:

      docker rmi test_test:latest ; docker-compose build && docker run -it --rm test_test:latest
      

      严重的是文档有些缺乏。

      参考:https://github.com/docker/compose/issues/1837

      【讨论】:

      • 我无法重现您的问题,您真的在评估 CMD 中的变量吗? CMD 是运行时间,而不是构建时间。
      • 是否可以将我的 .env 文件传递​​给 args?
      • Dockerfile 中的 ENV 变量实际上在构建阶段(即 RUN 命令)和运行容器中的环境变量中都可用。在此处查看文档:docs.docker.com/engine/reference/builder/#env
      猜你喜欢
      • 1970-01-01
      • 2021-03-05
      • 2022-08-04
      • 2017-06-04
      • 1970-01-01
      • 2020-04-28
      • 2019-02-25
      • 2019-03-25
      • 2019-10-10
      相关资源
      最近更新 更多