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

如何生成短有效期令牌从Artifact Registry拉取单个Docker容器?

用Node API生成Google Artifact Registry短有效期拉取令牌

前置准备

  • 提前为所用的Google Cloud服务账号分配roles/artifactregistry.reader权限,确保有目标镜像所在仓库的读取权限
  • Node项目中安装对应依赖包:npm install @google-cloud/artifact-registry google-auth-library

代码实现

生成的令牌为临时访问密码,固定用户名为oauth2accesstoken,有效期最大支持3600秒(1小时),可根据需求自定义更短的有效期:

const { ArtifactRegistryClient } = require('@google-cloud/artifact-registry');
const { GoogleAuth } = require('google-auth-library');

/**
 * 生成Artifact Registry短期拉取令牌
 * @param {string} projectId GCP项目ID
 * @param {string} location 镜像仓库所在区域,例:us-central1
 * @param {string} repository 镜像仓库名称
 * @param {number} expireSeconds 令牌有效期,单位秒,最大3600
 * @returns {object} 登录凭证信息
 */
async function generateShortLivedToken(
  projectId = '替换为你的GCP项目ID',
  location = '替换为仓库所在区域',
  repository = '替换为镜像仓库名',
  expireSeconds = 900 // 示例默认15分钟有效期
) {
  // 本地开发环境会自动读取gcloud auth的默认凭证,生产环境可在GoogleAuth中传入keyFilename参数指定服务账号密钥路径
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform'
  });
  const authClient = await auth.getClient();
  const accessToken = await authClient.getAccessToken();

  return {
    username: 'oauth2accesstoken',
    token: accessToken,
    expireSeconds
  }
}

// 调用示例
generateShortLivedToken().then(res => {
  console.log('登录用户名:', res.username);
  console.log('短期令牌:', res.token);
  console.log('有效期(秒):', res.expireSeconds);
})

使用生成的令牌通过Bash拉取Docker镜像

操作步骤

  • 第一步:登录Artifact Registry仓库,替换示例中的区域、令牌值即可
echo "替换为上一步生成的短期令牌" | docker login 仓库区域-docker.pkg.dev -u oauth2accesstoken --password-stdin

示例(区域为us-central1):

echo "ya29.xxxxxxx实际生成的令牌值" | docker login us-central1-docker.pkg.dev -u oauth2accesstoken --password-stdin
  • 第二步:拉取目标容器镜像,替换对应路径参数即可
docker pull 仓库区域-docker.pkg.dev/GCP项目ID/仓库名/镜像名:镜像标签

示例:

docker pull us-central1-docker.pkg.dev/my-project/my-repo/nginx:v1.25
  • 可选收尾操作:拉取完成后登出仓库,避免令牌遗留在本地Docker配置中
docker logout 仓库区域-docker.pkg.dev

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:18:03