如何评估Dockerfile中的环境变量?

时间:2020-03-31 13:16:43

标签: bash shell docker docker-compose environment-variables

我想使用存储在Dockerfile的.env文件中的本地环境变量的值,这几乎与docker-compose一样。我的脚本看起来像这样。

#!/bin/bash
source $(pwd)/.env

echo "Building new training container image..."
docker build \
        -t "rasa_training_img" \
        --build-arg RASA_VERSION \
        ./rasa-training

echo "Build finished. Running container..."
docker run \
        -v $(pwd)/rasa-server:/app \
        --name "rasa_training_cont" \
        rasa_training_img

Dockerfile看起来像这样:

# FROM rasa/rasa:1.9.4-spacy-de
FROM rasa/rasa:$RASA_VERSION-spacy-de

COPY ./utils /training-utils

# install necessary python packages
USER root
RUN pip install -r training-utils/requirements.txt
USER 1001

# execute training steps script
ENTRYPOINT [ "/bin/bash" ]
CMD [ "training_steps.sh" ]

当我尝试像这样运行它时,它会产生以下输出:

Step 1/7 : FROM rasa/rasa:$RASA_VERSION-spacy-de
invalid reference format

也用花括号试过了

Step 1/7 : FROM rasa/rasa:${RASA_VERSION}-spacy-de
invalid reference format

是否有一种方法来访问变量的值(就像使用docker-compose一样)? 我知道我基本上可以用docker-compose文件替换脚本,但是我想避免这种情况。

1 个答案:

答案 0 :(得分:0)

环境变量可以在发出docker build命令时作为构建参数传递。

在您的Dockerfile中,在FROM行上方添加以下内容。

ARG RASA_VERSION=${RASA_VERSION}
# FROM rasa/rasa:1.9.4-spacy-de
FROM rasa/rasa:${RASA_VERSION}-spacy-de
COPY ./utils /training-utils

# install necessary python packages
USER root
RUN pip install -r training-utils/requirements.txt
USER 1001

# execute training steps script
ENTRYPOINT [ "/bin/bash" ]
CMD [ "training_steps.sh" ]

在您的docker命令中执行

docker build --build-arg RASA_VERSION=${RASA_VERSION} -t imagename:tag .