如何将环境变量传递给 运行 命令
How to pass an environment variable into a RUN command
我有一个这样的 docker-compose.yml
文件:
version : '2'
services :
s1 :
build : .
environment :
HELLO : world
还有一个 Dockerfile
这样的:
FROM ubuntu
RUN /bin/bash -c 'echo "$HELLO" > /txt'
我怎样才能得到一个包含 txt
文件并在其中包含文本 world
的图像?
现在当我测试给定的例子时,文件是空的!
[更新]
如果我将环境变量放在 Dockerfile
中,它工作正常,这让我认为这是一个 docker-compose
问题!
FROM ubuntu
ENV HELLO=world
RUN /bin/bash -c 'echo "$HELLO" > /txt'
docker-compose.yml 中定义的环境在构建时将无法访问。
为此,您必须使用 build
字段的 args
选项(仅在 docker-compose 的第 2 版文件格式中受支持)。它会让你添加构建参数。
https://docs.docker.com/compose/compose-file/#args
在下面找到如何使用它:
docker-compose.yml
services :
s1 :
build :
context: .
args:
HELLO: world
此外,请注意,您必须在 Dockerfile 中定义具有相同键名的 ARG
标签。
FROM ubuntu
ARG HELLO
RUN echo "$HELLO" > /txt
我有一个这样的 docker-compose.yml
文件:
version : '2'
services :
s1 :
build : .
environment :
HELLO : world
还有一个 Dockerfile
这样的:
FROM ubuntu
RUN /bin/bash -c 'echo "$HELLO" > /txt'
我怎样才能得到一个包含 txt
文件并在其中包含文本 world
的图像?
现在当我测试给定的例子时,文件是空的!
[更新]
如果我将环境变量放在 Dockerfile
中,它工作正常,这让我认为这是一个 docker-compose
问题!
FROM ubuntu
ENV HELLO=world
RUN /bin/bash -c 'echo "$HELLO" > /txt'
docker-compose.yml 中定义的环境在构建时将无法访问。
为此,您必须使用 build
字段的 args
选项(仅在 docker-compose 的第 2 版文件格式中受支持)。它会让你添加构建参数。
https://docs.docker.com/compose/compose-file/#args
在下面找到如何使用它:
docker-compose.yml
services :
s1 :
build :
context: .
args:
HELLO: world
此外,请注意,您必须在 Dockerfile 中定义具有相同键名的 ARG
标签。
FROM ubuntu
ARG HELLO
RUN echo "$HELLO" > /txt