我有一个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