【问题标题】:Expand ARG value in CMD [Dockerfile]在 CMD [Dockerfile] 中展开 ARG 值
【发布时间】:2019-07-17 02:11:17
【问题描述】:

我将构建参数传递到:docker build --build-arg RUNTIME=test

在我的 Dockerfile 中,我想在 CMD 中使用参数的值:

CMD ["npm", "run", "start:${RUNTIME}"]

这样做会导致此错误:npm ERR! missing script: start:${RUNTIME} - 它没有扩展变量

我阅读了这篇文章:Use environment variables in CMD

所以我尝试这样做:CMD ["sh", "-c", "npm run start:${RUNTIME}"] - 我最终得到了这个错误:/bin/sh: [sh,: not found

当我运行构建的容器时会发生这两个错误。

我使用节点高山图像作为基础。任何人都知道如何让参数值在 CMD 中扩展?提前致谢!

完整的 Dockerfile:

FROM node:10.15.0-alpine as builder

ARG RUNTIME_ENV=test
RUN mkdir -p /usr/app
WORKDIR /usr/app

COPY . .

RUN npm ci
RUN npm run build

FROM node:10.15.0-alpine

COPY --from=builder /usr/app/.npmrc /usr/app/package*.json /usr/app/server.js ./
COPY --from=builder  /usr/app/config ./config
COPY --from=builder  /usr/app/build ./build

RUN npm ci --only=production

EXPOSE 3000

CMD ["npm", "run", "start:${RUNTIME_ENV}"]

更新: 为了清楚起见,我遇到了两个问题。 1. Samuel P. 描述的问题。 2、容器间不携带ENV值(多级)

这是我可以在 CMD 中扩展环境变量的工作 Dockerfile:

# Here we set the build-arg as an environment variable.
# Setting this in the base image allows each build stage to access it
FROM node:10.15.0-alpine as base
ARG ENV
ENV RUNTIME_ENV=${ENV}

FROM base as builder
RUN mkdir -p /usr/app
WORKDIR /usr/app
COPY . .
RUN npm ci && npm run build

FROM base
COPY --from=builder /usr/app/.npmrc /usr/app/package*.json /usr/app/server.js ./
COPY --from=builder  /usr/app/config ./config
COPY --from=builder  /usr/app/build ./build

RUN npm ci --only=production

EXPOSE 3000

CMD npm run start:${RUNTIME_ENV}

【问题讨论】:

  • 你能分享你完整的 Dockerfile 吗?
  • Dockerfile已编辑到帖子中,感谢查看

标签: docker dockerfile


【解决方案1】:

这里的问题是ARG 参数仅在映像构建期间可用。

ARG 指令定义了一个变量,用户可以在构建时使用docker build 命令使用--build-arg <varname>=<value> 标志将其传递给构建器。

https://docs.docker.com/engine/reference/builder/#arg

CMD 在容器启动时执行,此时ARG 变量不再可用。

ENV 变量在构建期间和容器中都可用:

使用 ENV 设置的环境变量将在容器从生成的图像运行时保持不变。

https://docs.docker.com/engine/reference/builder/#env

要解决您的问题,您应该将 ARG 变量转移到 ENV 变量。

CMD 之前添加以下行:

ENV RUNTIME_ENV ${RUNTIME_ENV}

如果你想提供一个默认值,你可以使用以下:

ENV RUNTIME_ENV ${RUNTIME_ENV:default_value}

Here 是 docker 文档中有关 ARGENV 用法的更多详细信息。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2021-04-25
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多