Docker CMD 无法读取节点应用程序中的参数

Docker CMD cant not read argument in node application

这是我的构建命令

docker build --build-arg APP_PROJ=proj1 --build-arg APP_ENV=dev -t proj1 .

给出两个参数,APP_ENVAPP_PROJ。这是我的 Dockerfile 内容

FROM node:14.15 AS build

ARG APP_ENV
ARG APP_PROJ

WORKDIR /usr/src/app

COPY package.json package-lock.json ./

RUN npm cache clean --force
RUN npm i

COPY . .

RUN npm run build:${APP_PROJ}:${APP_ENV}

CMD [ "node", "dist/${APP_PROJ}/server/main.js" ]

我想添加一个参数来证明正在构建哪个项目,但是当我 运行 docker 图片时,它返回了一个错误

Error: Cannot find module '/usr/src/app/dist/${APP_PROJ}/server/main.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)

at Function.Module._load (internal/modules/cjs/loader.js:725:27)

at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)

at internal/main/run_main_module.js:17:47{
 code: 'MODULE_NOT_FOUND',
 requireStack: []
}

看起来docker文件无法读取环境变量APP_PROJ。如何传递参数让docker读取正确的 main.js?

感谢帮助~

您似乎混淆了“ARGuments”和“ENVironments”。

doc 有助于理解差异。主要是关于:

ARG is only available during the build of a Docker image (RUN etc), not after the image is created and containers are started from it (ENTRYPOINT, CMD)

因此,您必须使用 ENV 变量来设置它们,以便您的 CMD 了解它们....
实际上,您可以在 documentation(同一网站)之后的构建时从 ARG 设置 ENV。这是常见的(不直观的)方式。

另一种方法是在 Dockerfile 中对它们进行硬编码(您可以在构建之前使用“sed”命令根据您的项目设置 DOckerfile)

另外:这可能不起作用,因为当您使用 CMD 作为参数列表时,不使用变量替换。您可能必须切换到原始 CMD (CMD dosomething "$myvar ${anotherVar}") 或使用 shell 形式的 CMD (CMD dosomething $myvar ${anotherVar})