引用Dockerfile中的Shell脚本变量



我有一个config.sh:

IMAGE_NAME="back_end"
APP_PORT=80
PUBLIC_PORT=8080

build.sh:

#!/bin/bash
source config.sh
echo "Image name is: ${IMAGE_NAME}"
sudo docker build -t ${IMAGE_NAME} .

run.sh:

#!/bin/bash
source config.sh
# Expose ports and run
sudo docker run -it 
-p $PUBLIC_PORT:$APP_PORT 
--name $IMAGE_NAME $IMAGE_NAME

最后是Dockerfile:

...
CMD ["gunicorn", "-b", "0.0.0.0:${APP_PORT}", "main:app"]

我希望能够在Dockerfile中引用config.sh中的APP_PORT变量,如上所示。然而,我所拥有的不起作用,它抱怨道:Error: ${APP_PORT} is not a valid port number。所以它并没有将APP_PORT解释为一个变量。有没有办法从Dockerfile中引用config.sh中的变量?

谢谢!

编辑:基于建议解决方案的新文件(仍然不起作用(

我有一个config.sh:

IMAGE_NAME="back_end"
APP_PORT=80
PUBLIC_PORT=8080

build.sh:

#!/bin/bash
source config.sh
echo "Image name is: ${IMAGE_NAME}"
sudo docker build --build-arg APP_PORT="${APP_PORT}" -t "${IMAGE_NAME}" .

和CCD_ 14:

#!/bin/bash
source config.sh
# Expose ports and run
sudo docker run -it 
-p $PUBLIC_PORT:$APP_PORT 
--name $IMAGE_NAME $IMAGE_NAME

最后是Dockerfile:

FROM python:buster
LABEL maintainer="..."
ARG APP_PORT
#ENV PORT $APP_PORT
ENV APP_PORT=${APP_PORT}
#RUN echo "$PORT"
# Install gunicorn & falcon
COPY requirements.txt ./
RUN pip3 install --no-cache-dir -r requirements.txt
# Add demo app
COPY ./app /app
COPY ./config.sh /app/config.sh
WORKDIR /app
RUN ls -a
CMD ["gunicorn", "-b", "0.0.0.0:${APP_PORT}", "main:app"]

run.sh仍然失败并报告:Error: '${APP_PORT} is not a valid port number.'

在Dockerfile中定义一个变量,如下所示:

FROM python:buster
LABEL maintainer="..."
ARG APP_PORT
ENV APP_PORT=${APP_PORT}

# Install gunicorn & falcon
COPY requirements.txt ./
RUN pip3 install --no-cache-dir -r requirements.txt
# Add demo app
COPY ./app /app
COPY ./config.sh /app/config.sh
WORKDIR /app
CMD gunicorn -b 0.0.0.0:$APP_PORT main:app     # NOTE! without separating with ["",""] 

将其作为build-arg传递,例如在您的build.sh:中

注意只有在用于构建docker映像时,才需要传递build参数。您可以在CMD上使用它,在构建docker映像时可以省略传递它。

#!/bin/bash
source config.sh
echo "Image name is: ${IMAGE_NAME}"
sudo docker build --build-arg APP_PORT="${APP_PORT}" -t "${IMAGE_NAME}" .
# sudo docker build --build-arg APP_PORT=80 -t back_end .           -> You may omit using config.sh and directly define the value of variables

启动容器时CCD_ 21在CCD_

#!/bin/bash
source config.sh
# Expose ports and run
sudo docker run -it 
-e APP_PORT=$APP_PORT 
-p $PUBLIC_PORT:$APP_PORT 
--name $IMAGE_NAME $IMAGE_NAME

您需要一个shell来替换环境变量,当您的CMD是exec形式时,就没有shell了。

如果使用shell形式,则存在一个shell,并且可以使用环境变量。

CMD gunicorn -b 0.0.0.0:${APP_PORT} main:app

有关CMD语句的两种形式的更多信息,请阅读此处:https://docs.docker.com/engine/reference/builder/#cmd

相关内容

  • 没有找到相关文章

最新更新