springboot使用docker-java连接docker所在的服务器操作docker

1.添加依赖,docker-java-core那个应该不用

        
            com.github.docker-java
            docker-java
			${docker.version}
            
                
                
                    io.netty
                    *
                
            
        
		
			com.github.docker-java
			docker-java-core
			${docker.version}
		
		
			com.github.docker-java
			docker-java-transport-httpclient5
			${docker.version}
		
		

其中版本控制


		3.2.11

2.添加配置文件docker-java.properties,其他的配置可以按需添加

DOCKER_HOST=tcp://xxx.xx.xx.xx:2375
registry.url=https://xxxxxxxx/
registry.username=xxxxxx
registry.password=xxxxxxx

追踪DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
springboot使用docker-java连接docker所在的服务器操作docker_第1张图片

3.业务类

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.InternalServerErrorException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.github.dockerjava.core.command.PullImageResultCallback;
import com.github.dockerjava.core.command.PushImageResultCallback;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
 * 本地docker管理类
 */
@Service
public class LocalDockerManager {

    private static final Logger log = LoggerFactory.getLogger(DockerManager.class);

    private DockerClient dockerClient;

    public LocalDockerManager() {
        this.init();
    }

    @Override
    /**
     * 初始化dockerClient
     */
    public DockerManager init() {
        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
        DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
                .dockerHost(config.getDockerHost())
                .sslConfig(config.getSSLConfig())
                .build();
        this.dockerClient = DockerClientImpl.getInstance(config, httpClient);
        return this;
    }

    /**
     * 拉取docker镜像
     *
     * @param image
     * @param secondsOfWait
     * @throws Exception
     */
    public void downloadDockerImage(String image, int secondsOfWait) throws InterruptedException {
            // 拉取镜像
            this.dockerClient.pullImageCmd(image).exec(new PullImageResultCallback()).awaitCompletion(secondsOfWait,
                    TimeUnit.SECONDS);
            log.info("Pull Docker image '{}' success", image);
    }

    /**
     * docker镜像是否本地已存在
     *
     * @param image
     * @return
     * @throws ProcessingException
     */
    public boolean dockerImageExistsLocally(String image) throws ProcessingException {
        boolean imageExists = false;
        try {
            this.dockerClient.inspectImageCmd(image).exec();
            imageExists = true;
        } catch (NotFoundException nfe) {
            imageExists = false;
        } catch (ProcessingException e) {
            throw e;
        }
        return imageExists;
    }

    /**
     * 通过本地是否存在hello-world镜像判断docker是否已经安装且可用
     *
     * @throws
     */
    public void checkDockerEnabled() {
        try {
            this.dockerImageExistsLocally("hello-world");
            log.info("Docker is installed and enabled");
        } catch (ProcessingException exception) {
            exception.printStackTrace();
//			throw new 
        }
    }

    @Override
    /**
     *  创建并运行容器
     */
    public String runContainer(String image, String containerName, String user,
                               List<Volume> volumes, List<Bind> binds, String networkMode, List<String> envs, List<String> command,
                               Long shmSize, boolean privileged, Map<String, String> labels) throws Exception {

        CreateContainerCmd cmd = dockerClient.createContainerCmd(image).withEnv(envs);
        if (containerName != null) {
            cmd.withName(containerName);
        }

        if (user != null) {
            cmd.withUser(user);
        }

        HostConfig hostConfig = new HostConfig().withNetworkMode(networkMode).withPrivileged(privileged);
        if (shmSize != null) {
            hostConfig.withShmSize(shmSize);
        }
        if (volumes != null) {
            cmd.withVolumes(volumes);
        }
        if (binds != null) {
            hostConfig.withBinds(binds);
        }

        if (labels != null) {
            cmd.withLabels(labels);
        }

        if (command != null) {
            cmd.withCmd(command);
        }

        cmd.withHostConfig(hostConfig);

        CreateContainerResponse response = null;
        try {
            response = cmd.exec();
            dockerClient.startContainerCmd(response.getId()).exec();
            log.info("Container ID: {}", response.getId());
            return response.getId();
        } catch (ConflictException e) {
            log.error(
                    "The container name {} is already in use. Probably caused by a session with unique publisher re-publishing a stream",
                    containerName);
            throw e;
        } catch (NotFoundException e) {
            log.error("Docker image {} couldn't be found in docker host", image);
            throw e;
        }
    }

    @Override
    /**
     * 删除容器
     */
    public void removeContainer(String containerId, boolean force) {
        dockerClient.removeContainerCmd(containerId).withForce(force).exec();
    }

    /**
     * 强制删除以xxx开始的容器
     *
     * @param imageName
     */
    public void cleanStrandedContainers(String imageName) {
        List<Container> existingContainers = this.dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container : existingContainers) {
            if (container.getImage().startsWith(imageName)) {
                log.info("Stranded {} Docker container ({}) removed on startup", imageName, container.getId());
                this.dockerClient.removeContainerCmd(container.getId()).withForce(true).exec();
            }
        }
    }

    /**
     * 得到运行中的container
     *
     * @param fullImageName
     * @return
     */
    public List<String> getRunningContainers(String fullImageName) {
        List<String> containerIds = new ArrayList<>();
        List<Container> existingContainers = this.dockerClient.listContainersCmd().exec();
        for (Container container : existingContainers) {
            if (container.getImage().startsWith(fullImageName)) {
                containerIds.add(container.getId());
            } else if (container.getImageId().contains(fullImageName)) {
                containerIds.add(container.getId());
            }
        }
        return containerIds;
    }

    /**
     * 得到imageId
     *
     * @param fullImageName
     * @return
     */
    public String getImageId(String fullImageName) {
        InspectImageResponse imageResponse = this.dockerClient.inspectImageCmd(fullImageName).exec();
        return imageResponse.getId();
    }

    /**
     * 给镜像打tag
     *
     * @param oldImageName  带tag
     * @param newImageName  不带tag
     * @param tag new镜像
     * @return
     */
    public void tagImage(String oldImageName, String newImageName, String tag) {
        this.dockerClient.tagImageCmd(oldImageName, newImageName, tag).exec();
        log.info("tag Docker image '{}' success", newImageName+":"+tag);
    }

	/**
	* push镜像到远端的私有huber仓库
	* name 镜像名
	* tag 
	**/
    public void pushImage(String name,String tagRes){
        PushImageCmd pushImageCmd = dockerClient.pushImageCmd(name).withTag(tagRes);
        PushImageResultCallback callback = new PushImageResultCallback() {
            @Override
            public void onNext(PushResponseItem item) {
                log.info(item.toString());
                super.onNext(item);
            }

            @Override
            public void onError(Throwable throwable) {
                log.error("Failed to exec start:" + throwable.getMessage());
                super.onError(throwable);
            }
        };
        pushImageCmd.exec(callback).awaitSuccess();
        log.info("push Docker image '{}' success", name+":"+tagRes);
    }

    /**
     * 获取远端仓库的所有镜像
     *
     * @return
     */
    public List<Image> listImages() {
        List<Image> images = this.dockerClient.listImagesCmd().exec();
        return images;
    }

    /**
     * 得到容器配置的标签
     *
     * @param containerId
     * @return
     */
    public Map<String, String> getLabels(String containerId) {
        InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();
        return containerInfo.getConfig().getLabels();
    }



    /**
     * 得到docker的基本信息
     */
    public void getInfo() {
        Info info = dockerClient.infoCmd().exec();
        System.out.println("docker的环境信息如下:=================");
        System.out.println(info);
    }

}

/**
 * 操作docker的业务类
 */
@Service
@Slf4j
public class DockerService {

    @Autowired
    private LocalDockerManager dockerManager;

    @Value("${xxx.outer-registry}")
    private String outerRegistry;

    @Value("${xxx.registry-prefix}")
    private String registryPrefix;

    @Value("${xxx.gray-scale-version}")
    private String grayScaleVersion;

    @Value("${xxx.inner-registry}")
    private String innerRegistry;


    /**
     * 拉取docker镜像
     */
    public boolean pullImage(String groupName, String projectName, String originVersion) {
        String imagePath = outerRegistry + "/" + registryPrefix + "/" + groupName + "/" + projectName + ":" + originVersion;
        try {
            dockerManager.downloadDockerImage(imagePath, 90);
            return true;
        } catch (NotFoundException | InternalServerErrorException e) {
            if (dockerManager.dockerImageExistsLocally(imagePath)) {
                log.info("Docker image '{}' exists locally", imagePath);
                return true;
            } else {
                log.error("Error on Pulling '{}' image.{}", imagePath,e);
            }
        } catch (DockerClientException e) {
            log.error("Error on Pulling '{}' image. Probably because the user has stopped the execution {}", imagePath,e);
        } catch (InterruptedException e) {
            log.error("Error on Pulling '{}' image. Thread was interrupted: {}", imagePath, e);
        }
        return false;
    }

    /**
     * 镜像推送到远程仓库
     */
    public void pushImage(String groupName, String projectName) {
        String newImageName = outerRegistry + "/" + registryPrefix + "/" + groupName + "/" + projectName + "-" + grayScaleVersion;
        dockerManager.pushImage(newImageName, grayScaleVersion);
    }

    /**
     * 给镜像打标签
     * @param groupName
     * @param projectName
     * @param originVersion
     */
    public boolean tagImage(String groupName, String projectName, String originVersion) {
        String imagePath = outerRegistry + "/" + registryPrefix + "/" + groupName + "/" + projectName + ":" + originVersion;
        String newImageName = outerRegistry + "/" + registryPrefix + "/" + groupName + "/" + projectName + "-" + grayScaleVersion;
        dockerManager.tagImage(imagePath, newImageName, grayScaleVersion);
        return dockerManager.dockerImageExistsLocally(newImageName);
    }

参考:https://blog.csdn.net/u010245179/article/details/107067530

springboot使用docker-java连接docker所在的服务器操作docker_第2张图片
遇到这种push记得绕道,我记得是不好使(。。)

参考链接:
关于k8s的B2I容器化完整解决方案,使用docker-java将jar包构建镜像并推送至远程镜像仓库,并能在k8s中运行
docker-java Docker的java API(。。)
java操作docker示例(docker-java)
JavaAPI 对Docker的系列操作

你可能感兴趣的:(工作总结)