多阶段构建中的Docker环境变量

问题描述 投票:4回答:2

鉴于此.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
2个回答
8
投票

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

看来ENV变量仅在运行容器时使用(docker-compose up)。不是在建设时间(docker-compose build)。所以你必须使用arguments

.ENV:

TEST=11111

泊坞窗,compose.yml:

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


2
投票

这不是具体的多阶段。

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

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

args

添加构建参数,这些参数只能在构建过程中访问。

Example from 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

Example to tie it back to the question:

the other answer in this thread.


Docs & deepening your understanding

Learn one layer of abstraction at a time

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

  1. Dockerfile(然后使用Dockerfile中的正在运行的容器...使用默认的ENV,然后使用--env,然后使用ARG--build-arg
  2. 然后添加docker-compose细节,并使用它们。
  3. 然后循环回Dockerfiles并理解多阶段构建。

Dockerfile

一篇有用的博客文章 - 专注于Dockerfile,但在所有情况下,最好先了解Dockerfiles,然后再添加额外的抽象层,例如docker-compose YAML。

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

from vsupalov.com post about this subject, https://vsupalov.com/docker-arg-env-variable-guide/

docker-compose

然后docker-撰写官方文档:

multi-stage Dockerfiles

© www.soinside.com 2019 - 2024. All rights reserved.