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

如何在Java中获取DockerHub镜像层?Jib工具尝试失败求助

解决Jib拉取Docker Hub镜像清单的问题

问题原因分析

  • 404错误:你使用的registry.hub.docker.com不是Docker Hub的正确API地址,官方API端点应为registry-1.docker.io。
  • 401错误:Docker Hub目前要求拉取公开镜像也需提供匿名认证令牌,直接使用library/ubuntu但未处理认证会触发权限校验失败。

可行实现方式

以下是调整后的代码,处理认证流程并使用正确的Registry地址:

import com.google.cloud.tools.jib.api.RegistryClient;
import com.google.cloud.tools.jib.http.FailoverHttpClient;
import com.google.cloud.tools.jib.http.HttpClient;
import com.google.cloud.tools.jib.registry.RegistryAuthenticator;
import com.google.cloud.tools.jib.registry.RegistryCredentials;
import com.google.cloud.tools.jib.event.EventHandlers;

public class JibRegistryExample {
    public static void main(String[] args) throws Exception {
        // Docker Hub官方API地址
        String registry = "registry-1.docker.io";
        // 官方镜像需带library/前缀
        String imageName = "library/ubuntu";
        String tag = "latest";

        // 创建HttpClient实例
        HttpClient httpClient = new FailoverHttpClient(true, false, ignored -> {});

        // 获取匿名认证令牌(Docker Hub公开镜像必填)
        RegistryCredentials anonymousCredentials = RegistryCredentials.anonymous();
        RegistryAuthenticator authenticator = RegistryAuthenticator.forImage(
                registry,
                imageName,
                anonymousCredentials,
                httpClient,
                EventHandlers.NONE
        );
        String authToken = authenticator.authenticate().getAuthorizationHeader();

        // 初始化带认证的RegistryClient
        RegistryClient client = RegistryClient.factory(EventHandlers.NONE, registry, imageName, httpClient)
                .setAuthorizationHeader(authToken)
                .newRegistryClient();

        // 拉取镜像清单
        var manifest = client.pullManifest(tag);
        var template = manifest.getManifest();
        
        // 验证结果(可选)
        System.out.println("清单媒体类型: " + template.getMediaType());
        System.out.println("清单 schema 版本: " + template.getSchemaVersion());
    }
}

关键调整点

  • 替换Registry地址为registry-1.docker.io:registry.hub.docker.com是Web UI地址,不用于API请求,必须使用官方API端点。
  • 添加匿名认证流程:通过RegistryAuthenticator获取匿名令牌,满足Docker Hub的认证要求,公开镜像也需此步骤。
  • 显式设置认证头:将令牌传入RegistryClient,确保请求通过权限校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:05:26