欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實現(xiàn)docker鏡像上傳到harbor倉庫的方式

 更新時間:2025年06月27日 16:51:49   作者:yuhuofei2021  
這篇文章主要介紹了java實現(xiàn)docker鏡像上傳到harbor倉庫的方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1. 前 言

在推送鏡像文件到鏡像倉庫時,我們往往是在鏡像文件所在的那個主機上,以 root 用戶的權(quán)限,執(zhí)行 docker push 命令,完成鏡像推送的工作。

但有這么一種令人匪夷所思的人,他直接打一個離線的鏡像包(docker save tomcat:latest > tomcat-892148dsadg-v1.tar)出來,比如 tomcat-892148dsadg-v1.tar ,然后通過郵件或者其它通訊工具發(fā)給你,讓你推送到鏡像倉庫。

這時,你怎么搞?直接通過 shell 指令操作,可行嗎?當(dāng)然可以,只要在有 docker 環(huán)境的服務(wù)器上,

以 root 權(quán)限的用戶執(zhí)行下面 5 步就能完成:

  • rz 命令,上傳 tar 包到服務(wù)器上
  • docker load -i xxxx.tar ,加載鏡像文件
  • docker login harbor倉庫地址 -u 用戶名 -p 密碼 ,登錄 harbor 倉庫
  • docker tag xxxx.tar harbor倉庫地址/命名空間/xxxxx.tar,重新打標(biāo)簽
  • docker push harbor倉庫地址/命名空間/xxxxx.tar,推送鏡像到 harbor 倉庫

上面的方式,看著是很清晰地解決了問題,但一般來說,開發(fā)人員很少能直接操控服務(wù)器,更別提拿到 root 用戶,在一些權(quán)限管控嚴格的企業(yè),這種方式想想就好了,或者讓運維來。

那還有其它方式嗎?當(dāng)然!那就直接用 java 操作 docker 命令實現(xiàn)離線的 tar包 推送至 harbor 倉庫吧!

2. 編寫工具類

2.1 引入依賴包

  • 在 pom.xml 文件中引入下面的兩個依賴
<dependency>
    <groupId>com.github.docker-java</groupId>
    <artifactId>docker-java</artifactId>
    <version>3.2.13</version>
</dependency>
<dependency>
    <groupId>com.github.docker-java</groupId>
    <artifactId>docker-java-transport-httpclient5</artifactId>
    <version>3.2.13</version>
</dependency>

2.2 使用當(dāng)前服務(wù)器的docker環(huán)境推送鏡像

  • application.properties 配置文件
harbor.username=harbor
harbor.password=Harbor123!
  • 工具類
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;

/**
 * @author yuhuofei
 * @version 1.0
 * @description 鏡像上傳工具類
 * @date 2022/6/13 21:19
 */
@Service
@Slf4j
public class DockerUtils {

    @Value("${harbor.username}")
    private String harborUserName;

    @Value("${harbor.password}")
    private String harborPassWord;

    /**
     * 獲取dockerClient對象
     */
    public DockerClient getDockerClient() {
    
        //創(chuàng)建DefaultDockerClientConfig(當(dāng)前服務(wù)器的默認配置)
        DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();

        //創(chuàng)建DockerHttpClient
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(config.getDockerHost())
                .maxConnections(100)
                .connectionTimeout(Duration.ofSeconds(30))
                .responseTimeout(Duration.ofSeconds(45))
                .build();

        //創(chuàng)建DockerClient
        return DockerClientImpl.getInstance(config, httpClient);

    }

    /**
     * @param file      鏡像文件
     * @param imageName 鏡像名稱,格式最好是:鏡像名-鏡像id-版本號.tar
     * @param harborLoginUrl harbor倉庫地址
     * @param imageId 鏡像id
     * @param tag 版本號
     */
    public void uploadImage(File file, String imageName, String harborLoginUrl, String imageId, String tag) {
        log.info("上傳鏡像文件時,傳遞的參數(shù):{},{},{},{},{}", file.getAbsolutePath(), imageName, harborLoginUrl, imageId, tag);
        try (InputStream inputStream = new FileInputStream(file)) {
            DockerClient dockerClient = getDockerClient();
            //Harbor登錄信息
            AuthConfig autoConfig = new AuthConfig().withRegistryAddress(harborLoginUrl).withUsername(harborUserName).withPassword(harborPassWord);

            //加載鏡像
            log.info("====開始加載鏡像====,{}", inputStream);
            dockerClient.loadImageCmd(inputStream).exec();
            
            //獲取加載鏡像的名稱,如果根據(jù)鏡像名稱去匹配,有可能重復(fù),所以用鏡像id去匹配
            String uploadImageName = "";
            List<Image> list = dockerClient.listImagesCmd().exec();
            for (Image image : list) {
                if (image.getId().contains(imageId)) {
                    uploadImageName = image.getRepoTags()[0];
                }
            }

            //給鏡像打上tag
            log.info("原始鏡像名:{},要修改的鏡像名:{}", uploadImageName, imageName);
            dockerClient.tagImageCmd(uploadImageName, imageName, tag).exec();

            //推送鏡像至鏡像倉庫
            dockerClient.pushImageCmd(imageName).withAuthConfig(autoConfig).start().awaitCompletion();
            //push成功后,刪除本地加載的鏡像
            dockerClient.removeImageCmd(imageName).exec();
            dockerClient.removeImageCmd(uploadImageName).exec();
        } catch (InterruptedException exception) {
            throw new BaseException("推送鏡像到鏡像倉庫異常:{}", exception);
        } catch (IOException e) {
            throw new BaseException("鏡像文件流處理異常");
        }
    }
}

2.2 使用指定服務(wù)器的docker環(huán)境推送鏡像

  • application.properties 文件的配置
docker.server.url=tcp://xxxxxx:2376
docker.cert.path=/home/user/.docker/certs
api.version=1.41
registry.url=https://index.docker.io/v1/
registry.username=docker
registry.password=Docker123!
registry.email=xxxxxxx@qq.com

harbor.username=harbor
harbor.password=Harbor123!
  • 工具類
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;

/**
 * @author yuhuofei
 * @version 1.0
 * @description 鏡像上傳工具類
 * @date 2022/6/13 21:19
 */
@Service
@Slf4j
public class DockerUtils {

    @Value("${docker.server.url}")
    private String dockerServerUrl;
    
    @Value("${docker.cert.path}")
    private String dcokerCertPath;

    @Value("${registry.user}")
    private String registryUser;
    
    @Value("${registry.pass}")
    private String registryPass;
    
    @Value("${registry.mail}")
    private String registryMail;
    
    @Value("${registry.url}")
    private String registryUrl;

	//harbor倉庫登錄用戶名
    @Value("${harbor.username}")
    private String harborUserName;
	//harbor倉庫登錄密碼
    @Value("${harbor.password}")
    private String harborPassWord;

    /**
     * 獲取dockerClient對象
     */
    public DockerClient getDockerClient() {
    
        //創(chuàng)建DefaultDockerClientConfig(指定docker服務(wù)器的配置)
        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost(dockerServerUrl)
    		.withDockerTlsVerify(true)
    		.withDockerCertPath(dcokerCertPath)
    		.withRegistryUsername(registryUser)
    		.withRegistryPassword(registryPass)
    		.withRegistryEmail(registryMail)
    		.withRegistryUrl(registryUrl)
    		.build();

        //創(chuàng)建DockerHttpClient
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(config.getDockerHost())
                .maxConnections(100)
                .connectionTimeout(Duration.ofSeconds(30))
                .responseTimeout(Duration.ofSeconds(45))
                .build();

        //創(chuàng)建DockerClient
        return DockerClientImpl.getInstance(config, httpClient);

    }

    /**
     * @param file      鏡像文件
     * @param imageName 鏡像名稱,格式最好是:鏡像名-鏡像id-版本號.tar
     * @param harborLoginUrl harbor倉庫地址
     * @param imageId 鏡像id
     * @param tag 版本號
     */
    public void uploadImage(File file, String imageName, String harborLoginUrl, String imageId, String tag) {
        log.info("上傳鏡像文件時,傳遞的參數(shù):{},{},{},{},{}", file.getAbsolutePath(), imageName, harborLoginUrl, imageId, tag);
        try (InputStream inputStream = new FileInputStream(file)) {
            DockerClient dockerClient = getDockerClient();
            //Harbor登錄信息
            AuthConfig autoConfig = new AuthConfig().withRegistryAddress(harborLoginUrl).withUsername(harborUserName).withPassword(harborPassWord);

            //加載鏡像
            log.info("====開始加載鏡像====,{}", inputStream);
            dockerClient.loadImageCmd(inputStream).exec();
            
            //獲取加載鏡像的名稱,如果根據(jù)鏡像名稱去匹配,有可能重復(fù),所以用鏡像id去匹配
            String uploadImageName = "";
            List<Image> list = dockerClient.listImagesCmd().exec();
            for (Image image : list) {
                if (image.getId().contains(imageId)) {
                    uploadImageName = image.getRepoTags()[0];
                }
            }

            //給鏡像打上tag
            log.info("原始鏡像名:{},要修改的鏡像名:{}", uploadImageName, imageName);
            dockerClient.tagImageCmd(uploadImageName, imageName, tag).exec();

            //推送鏡像至鏡像倉庫
            dockerClient.pushImageCmd(imageName).withAuthConfig(autoConfig).start().awaitCompletion();
            //push成功后,刪除本地加載的鏡像
            dockerClient.removeImageCmd(imageName).exec();
            dockerClient.removeImageCmd(uploadImageName).exec();
        } catch (InterruptedException exception) {
            throw new Exception("推送鏡像到鏡像倉庫異常:{}", exception);
        } catch (IOException e) {
            throw new Exception("鏡像文件流處理異常");
        }
    }
}

3. 說 明

  • 上述的 java 服務(wù),不能部署在 docker 環(huán)境的容器內(nèi),需要部署在 docker 主機上,不然在容器中運行的 java 服務(wù),是沒法操作到主機上的 docker 命令的
  • 上傳 tar 包文件的前端內(nèi)容省略
  • 這里上傳的 tar 包命名格式最好是:鏡像名-鏡像id-版本號.tar
  • 打出來的 tar 包,大小最好不要超過 20 G

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot中集成串口通信的項目實踐

    SpringBoot中集成串口通信的項目實踐

    本文主要介紹了SpringBoot中集成串口通信,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-08-08
  • spring?security?自定義Provider?如何實現(xiàn)多種認證

    spring?security?自定義Provider?如何實現(xiàn)多種認證

    這篇文章主要介紹了spring?security?自定義Provider實現(xiàn)多種認證方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • AI算法實現(xiàn)五子棋(java)

    AI算法實現(xiàn)五子棋(java)

    這篇文章主要為大家詳細介紹了AI算法實現(xiàn)五子棋,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • Java中indexOf()的用法小結(jié)

    Java中indexOf()的用法小結(jié)

    這篇文章主要介紹了Java中indexOf()的用法小結(jié),indexOf()有四種方法,用來查找某個字符或字符串的位置,本文通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2024-01-01
  • 解決IDEA創(chuàng)建第一個spring boot項目提示cannot resolve xxx等錯誤

    解決IDEA創(chuàng)建第一個spring boot項目提示cannot resolve xxx等

    這篇文章主要介紹了解決IDEA創(chuàng)建第一個spring boot項目提示cannot resolve xxx等錯誤問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • spring使用redis操作key-value的示例代碼

    spring使用redis操作key-value的示例代碼

    這篇文章主要介紹了spring使用redis操作key-value的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • Java一元稀疏多項式計算器

    Java一元稀疏多項式計算器

    大家好,本篇文章主要講的是Java一元稀疏多項式計算器,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • kotlin之閉包案例詳解

    kotlin之閉包案例詳解

    這篇文章主要介紹了kotlin之閉包案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • 關(guān)于SpringCloud分布式系統(tǒng)中實現(xiàn)冪等性的幾種方式

    關(guān)于SpringCloud分布式系統(tǒng)中實現(xiàn)冪等性的幾種方式

    這篇文章主要介紹了關(guān)于SpringCloud分布式系統(tǒng)中實現(xiàn)冪等性的幾種方式,冪等函數(shù),或冪等方法,是指可以使用相同參數(shù)重復(fù)執(zhí)行,并能獲得相同結(jié)果的函數(shù),這些函數(shù)不會影響系統(tǒng)狀態(tài),也不用擔(dān)心重復(fù)執(zhí)行會對系統(tǒng)造成改變,需要的朋友可以參考下
    2023-10-10
  • 解決java main函數(shù)中的args數(shù)組傳值問題

    解決java main函數(shù)中的args數(shù)組傳值問題

    這篇文章主要介紹了解決java main函數(shù)中的args數(shù)組傳值問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02

最新評論