You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地Docker构建时使用Google应用默认凭据访问私有npm包失败

本地Docker构建访问Google Artifact Registry私有npm包解决方案

问题原因

本地执行Docker构建时,仅通过--build-arg传递本地凭据路径无效——容器内不存在该路径下的文件,导致google-artifactregistry-auth无法读取ADC凭据。

解决方法

方法1:挂载本地ADC凭据到构建容器

通过Docker构建的--mount参数,将本地的应用默认凭据文件挂载到容器内对应路径,同时设置环境变量指向容器内的路径:

docker build \
  --mount type=bind,source="$HOME/.config/gcloud/application_default_credentials.json",target=/root/.config/gcloud/application_default_credentials.json \
  --build-arg GOOGLE_APPLICATION_CREDENTIALS=/root/.config/gcloud/application_default_credentials.json \
  -t hello_world .

macOS下$HOME会自动映射到当前用户目录,确保本地凭据路径正确。

方法2:使用服务账号密钥文件

如果挂载ADC凭据存在权限问题,可改用GCP服务账号密钥:

  1. 在GCP控制台创建服务账号,授予Artifact Registry Reader权限,下载密钥文件到本地(命名为service-account-key.json)
  2. 执行构建命令:
docker build \
  --mount type=bind,source="./service-account-key.json",target=/root/service-account-key.json \
  --build-arg GOOGLE_APPLICATION_CREDENTIALS=/root/service-account-key.json \
  -t hello_world .

方法3:预先生成带凭据的.npmrc文件

本地先生成包含Artifact Registry访问凭据的.npmrc,再复制到镜像中完成安装:

  1. 本地执行命令生成凭据:
npx google-artifactregistry-auth
  1. 修改Dockerfile,添加复制.npmrc的步骤:
# 复制本地生成的带凭据的.npmrc
COPY .npmrc .
# 执行依赖安装
RUN npm install
# 可选:安装完成后删除.npmrc,避免凭据泄露
RUN rm .npmrc
  1. 执行构建:
docker build -t hello_world .

内容的提问来源于stack exchange,提问作者zaitsman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:35:24