Dockerfile:在RUN指令之间不保留附加变量 [英] Dockerfile: An appended variable is not persisted between RUN instructions

查看:210
本文介绍了Dockerfile:在RUN指令之间不保留附加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经导出了变量,以确保即使在新的shell实例中,该变量也可以保留,但是它不起作用...
我不知道该怎么做。
我已经做了很多研究和测试,没有定论。

I have exported the variables to make sure that even in a new instance of the shell the variable is persisted but it doesn't work... I don't know how I should do it. I've done a lot of research and testing, nothing conclusive.

Dockerfile:

Dockerfile:

FROM bitnami/minideb:stretch

SHELL ["/bin/bash", "-c"]

ARG VAR1="1"
ARG VAR2="Hello"

# Export arguments
RUN export VAR1="${VAR1}" \
    && export VAR2="${VAR2}"

# Output "Hello world"
RUN if [ $VAR1 = "1" ]; then VAR2+=" world"; fi \
    && echo $VAR2

# Output "Hello" instead of "Hello World"
RUN echo $VAR2

确保每个 RUN 都发生在新的外壳中。

For sure each RUN happens in a new shell.

但是为什么heck VAR2 + = world 不持久,因为 export VAR2 = $ {VAR2} 持久?

But why the heck VAR2+=" world" is not persisted since export VAR2="${VAR2} is persisted?

我真的不明白。

在此先感谢任何找到解决这种奇怪行为方法的人。

Thanks in advance to anyone who finds a way to tackle this odd behaviour.

推荐答案

根据文档,您可以使用 -e之一传递环境变量, --env,-env文件或bash的导出,就像上面一样。

According to documentation you can either pass environment variable using either of -e, --env, --env-file or bash's export as you did above.

您无法使用 bash 脚本设置变量,请尝试 export 另一个变量(例如

You cannot set the variable using bash script, try to export another variable (say VAR3) inside your if clause.

在if子句中可以看到VAR3 )。类似于此答案,但这确实很丑陋:

You can go with something like this answer, but it's really ugly:

FROM bitnami/minideb:stretch

SHELL ["/bin/bash", "-c"]

ARG VAR1="1"
ARG VAR2="Hello"

# Export arguments
RUN export VAR1="${VAR1}" \
    && export VAR2="${VAR2}"

RUN echo 'if [ $VAR1 = "1" ]; then VAR2+=" world"; fi' > ~/.bashrc

# Output "Hello" instead of "Hello World"
RUN source ~/.bashrc && echo "$VAR2"

您可以编写脚本( my_env 以上)从Docker文件外部并从其内部获取,或使用 -e,-env,-env-file ,后者要好得多

You could make your script (my_env above) outside of the Docker file and source it from within, or use -e, --env, --env-file, the latter being much better.

这篇关于Dockerfile:在RUN指令之间不保留附加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆