Docker 和私有模块

要在 Docker 容器中安装私有 npm 包,您需要使用 Docker 构建密钥

背景:运行时变量

您不能仅使用运行时变量在 Docker 容器中安装私有 npm 包。考虑以下 Dockerfile:

FROM node

COPY package.json package.json
RUN npm install

# Add your source files
COPY . .
CMD npm start

它将使用官方的 Node.js 镜像,将 package.json 复制到我们的容器中,安装依赖项,复制源文件并运行 package.json 中指定的启动命令。

为了安装私有包,你可能认为我们可以在运行 npm install 之前添加一行,使用 ENV 参数

ENV NPM_TOKEN=00000000-0000-0000-0000-000000000000

但是,这并不像您期望的那样工作,因为您希望在运行 docker build 时发生 npm install,并且在这种情况下,不使用 ENV 变量,它们仅设置为运行时。

m7L7OKOxnJB4yOnODg2fOwKdT23UlxURKWDVOmrw393NSTydtuYik2NeylMBLWfitOcbUCWBWaFfIib9iL9yWSwGKNCgAg7xzJpo5QjNpyM=

更新 Dockerfile

9LsyIEMoSgJHusW/tWYT5TuFUvJKArSLJHQvBFGYZLkcsT2qtacpFeTQ3T/G8CmbhWDRX1R3j964tdCfidsFoIG+HojNng0Se+6Mzz0lTA5czt1VJ8oO+t5usS++a/PtbjV4/j9+QKnwyMM6joMDyWzr2mq7L0or7oh5MWDONNLvv01bWcZ8gV9o+TBeUmOE4CWe1ZG4qOH7630Ylvr4517MdHDRgJVMwIDhWKF1OD7LYCFImECXx9zgK8XecWHh+yB2SA/oDEp0rIzd2vgA3z4fNo1cttXIZaY5BUMMC+sCuThg6cGwY3aMdaxFSOTn9QC2hlQnjwRnPsRHitbpeQ==

# https://docs.npmjs.com/docker-and-private-modules
FROM node:18

ENV APP_HOME="/app"

WORKDIR ${APP_HOME}

COPY package*.json ${APP_HOME}/

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm install

COPY . ${APP_HOME}/

CMD npm start

SHR5srsmxSub9E6Cwi3/b3yk3cWdk1MtnpYJHMkWHLBxGfMocJGi9Ezxy9yRQzoLMKhs5VAQ89cxnj0+WTNcHIh2xpHYFmJt2CNHKXp7vUqbOFJH90VRPHN2j4sDp7ylPoai9LY/YOfvNI+TWEIlWZaOhRWVFG8ajsgq6ba8sgrWwVO28NTKqxRoR71epDcdB8gHYNmrcj6s2YdIIcKfLw==

构建 Docker 镜像

MUJAJH6GzOORtk+oLgWw7DcTvmfscS06FHLVOsY98HPmTsAkAJbOfc6Ss8pBynpenfF+Pfk5YNAaCQ8Qd9GyGWuJMnbFF7E25o76SWdInXMKNtS5TMfWHLesnkRrZ7UaEdpNCGva8PuedflyxTksNq3FrRNfCHzwDM9drvIvDoBj5RgHuJF6FHC9UELVh4hSn0ZEpWgjp40RlpNFd0dTHoYHzgTzWu4vzBm/WiV4CqK7kbSc11RsTNuif7oNwxl6QCvmfzkqxSRrA6Y6nJZGCg==

docker build . -t secure-app-secrets:1.0 --secret id=npmrc,src=$HOME/.npmrc

utcfQXcUgLgfE2c90iJj2QziX2wkp06nC2ZYS9/MJ8ezRWs2k5ZphnJP1gBG5HWDSUfogxkF1b/SF7lJV8FEh+keHjSBSNaF76fxG0JXkNrjDjEQuLYXMw36IeH5/xBzFgjIaSepXjFAf8f6Om1jab2bBIZfYi1fCINHJ/YVUo3Yo6rbuz+UH2P7qfM5DYEigF3ANwHsZzDc3XEe6JqodFN7vE0zYSrOrV89pPbIh5qAjyHtXzSytQGNLHpHU+Ht7+VdyNspiwUrrp3PYU8+jg==

JoAYhwM37o6CvJtLLcIJnkR6a8gp9Pw1Kg7hKucGfvLWzOYHAYI1HYx2A5HP7LC6o5zVqV93BdQQMhgyhE6tKKfkNHoy/tj/M0cb0eWO6XGVNaM+6IwbYTWoe/1UFKGdX4aJPFH+e9FSOJ6golZ9hVldcE+IsYCoJsHLVP6b9uEMsorHhNG2aGRXlvG2gCb7