Dockerfile 将 ENV 传递给 ENTRYPOINT 或 CMD

Dcokerfile pass ENV to ENTRYPOINT or CMD

我正在尝试根据构建时传递的 arg 启动应用程序

命令: docker build --build-arg profile=live . -t app

Docker 文件:

FROM openjdk:11.0.7-jre-slim-buster

WORKDIR /app
ARG JAR_FILE=target/*.jar

ARG profile
ENV profile ${profile:-dev}

EXPOSE 8080
COPY ${JAR_FILE} /app/app.jar

# ENTRYPOINT ["java", "-jar", "app.jar", "--spring.profiles.active=${profile}"]   --- not working

RUN echo $profile   <--- here I got the value
#CMD java -jar app.jar --spring.profiles.active=${profile}   --- not working
#CMD java -jar app.jar --spring.profiles.active=$profile   --- not working
CMD ["sh", "-c", "node server.js ${profile}"]   --- not working

当我检查 docker 图像时,我得到

"Cmd": [
            "sh",
            "-c",
            "node server.js ${profile}"
        ],

我错过了什么?

谢谢

更新: 与 CMD java -jar app.jar --spring.profiles.active=$profile 一起工作并且 $profile 将在运行时具有所需的值

CMD 中未发生环境替换。相反,它发生在容器内的 shell 运行 中(在你的例子中是 sh,尽管不清楚你为什么使用 json/exec 语法来调用 sh命令)。

有关环境替换的文档可从以下位置获得:https://docs.docker.com/engine/reference/builder/#environment-replacement

试试这个 Dockerfile:docker build --build-arg PROFILE=uat -t app .

FROM alpine
ARG PROFILE
ENV PROFILE ${PROFILE:-dev}
CMD ["ash", "-c", "while :; do echo $PROFILE; sleep 1; done"]

运行 它每秒打印 uatdocker run -it --rm app

当你说“不起作用”时,你没有提到具体的结果是什么。假设您得到空字符串或其他意外值,环境变量可能被基础映像使用。为您的环境变量尝试另一个名称,或使用非 slim 版本的 openjdk 图像。