从脚本获取环境变量并传递给Dockerfile

时间:2018-12-19 20:38:32

标签: bash shell docker environment-variables dockerfile

我有一个像这样的 script.sh

DATE="R_$(date +%Y_%m_%d__%H_%M_%S)"
export DISTDIR="$BUILDDIR/$DATE"

我不会这样在我的 Dockerfile 中传递此DISTDIR

COPY build/$DISTDIR/ "$CATALINA_HOME"/webapps/ws/js/

我是怎么做到的,我搜索了各种模式,但没有一个工作

1 个答案:

答案 0 :(得分:0)

问题在于传递环境变量,而不是如何设置环境变量(是否设置dotenv)或如何使用环境变量(设置变量或COPY)。

这是使用from the duplicate技术的完整演示。这是script.sh

#!/bin/bash
mycustomvar="file.$RANDOM"
touch "$mycustomvar"
echo "I am running outside Docker with mycustomvar=$mycustomvar"
docker build --build-arg mycustomvar="$mycustomvar" .

还有一个Dockerfile

FROM alpine
ARG mycustomvar
RUN echo "I am running in docker with mycustomvar=$mycustomvar"
COPY $mycustomvar /tmp/
RUN ls /tmp

运行时会发生以下情况:

$ sudo ./script.sh
I am running outside Docker with mycustomvar=file.10518
Sending build context to Docker daemon  17.41kB
Step 1/5 : FROM alpine
 ---> 3fd9065eaf02
Step 2/5 : ARG mycustomvar
 ---> Using cache
 ---> a6dfa6001164
Step 3/5 : RUN echo "I am running in docker with mycustomvar=$mycustomvar"
 ---> Running in e958044bfd11
I am running in docker with mycustomvar=file.10518
 ---> 95c107e49291
Removing intermediate container e958044bfd11
Step 4/5 : COPY $mycustomvar /tmp/
 ---> d36445b49261
Removing intermediate container e3ac014d1ba9
Step 5/5 : RUN ls /tmp
 ---> Running in 590409a81df5
file.10518
 ---> d734f83cc8ec
Removing intermediate container 590409a81df5
Successfully built d734f83cc8ec

如您所见,script.sh设置了一个变量,并且RUN和COPY语句都可以访问它。