Dockerfile CMD未按预期执行bash脚本,例如set-env.sh
中的echo命令未执行
首先,我将一个env变量传递给Dockerfile使用的图像
docker build -f Dockerfile --pull --build-arg env=prod -t test-app .
这是Dockerfile我使用
# Multi-stage
# 1) Node image for building frontend assets
# 2) nginx stage to serve frontend assets
# Name the node stage "builder"
FROM node:16 AS builder
# Set working directory
WORKDIR /project
# Copy all files from current directory to working dir in image
COPY . .
# install node modules and build assets
RUN yarn install --network-timeout 100000 && yarn build
# nginx state for serving content
FROM nginx:alpine
# Nginx config
RUN rm -rf /etc/nginx/conf.d
COPY conf /etc/nginx
# Set working directory to nginx asset directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static assets
RUN rm -rf ./*
# Copy static assets from builder stage
COPY --from=builder /project/build .
# Set enviorment so the set-env.sh script can read the correct env file
ARG env
ENV ENVIRONMENT=$env
# these statements print out the env vars as expected during the build
RUN echo $env
RUN echo $ENVIRONMENT
# Default port exposure
EXPOSE 443
# Copy environment file and script into container
COPY ./set-env.sh .
# Add bash
RUN apk add --no-cache bash
# Containers run nginx with global directives and daemon off
CMD ["/bin/bash", "-c", "/usr/share/nginx/html/set-env.sh && nginx -g 'daemon off;'"]
set-env.sh(参考上面最后一行Dockerfile
)
#!/bin/bash
# Recreate config file
rm -rf ./env-config.js
touch ./env-config.js
# Choose the .env file base on "ENV" defined in the DockerFile
if [ $env == "dev" ]; then
echo "TEST: DEV " >> ./env-config.js
elif [ $env == "prod" ]; then
echo "TEST: PROD " >> ./env-config.js
else
echo "Unsupported environment"
exit 1
fi
上面没有向env-config.js
返回任何东西-不知道为什么。
然而,每当我从容器内手动运行set-env.sh
时,它就会像预期的那样工作,例如根据传递给docker构建命令的env参数打印出DEV或PROD测试行到env-config.js
任何想法?
感谢大家提供的信息。
这个问题与我测试脚本的方式有关。我运行了以下命令,并登录到容器中查看实际发生了什么。
docker run test-app tail -F asdflg
在我不知道的情况下,tail命令,虽然允许容器运行,实际上似乎在我的Dockerfile的最后一行阻止了CMD的处理…一旦我用docker compose up
代替运行容器,一切都像预期的那样工作。
在Dockerfile中,您设置了变量ENVIRONMENT
,但在脚本中,您在变量env
上进行测试。
构建参数变量不作为环境变量传递,所以你不能使用env
没有在Dockerfile中设置。
要么改变
ENV ENVIRONMENT=$env
ENV env=$env
或将脚本if
语句更改为
if [ $ENVIRONMENT == "dev" ]; then
echo "TEST: DEV " >> ./env-config.js
elif [ $ENVIRONMENT == "prod" ]; then
echo "TEST: PROD " >> ./env-config.js
else
echo "Unsupported environment"
exit 1
fi