Docker Java API creates containers and maps ports

preparation conditions

Make sure port 2375 is enabled, if not, follow the steps below to enable it:

vim /lib/systemd/system/docker.service
# 修改如下行
# ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
# 改为如下
ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock
# 重启
systemctl daemon-reload
systemctl restart docker

Maven adds dependencies

Add the following dependencies to the POM:

<!-- https://mvnrepository.com/artifact/com.github.docker-java/docker-java -->
<dependency>
    <groupId>com.github.docker-java</groupId>
    <artifactId>docker-java</artifactId>
    <version>3.2.13</version>
</dependency>

The version 3.2.13 is used here. You can choose the version yourself. Different versions may be written differently.

Write tool class

Create the DockerUtils class:

public class DockerUtils {
    
    
    // 定义dockerClient操作docker
    private DockerClient dockerClient;
    // 重新定义无参构造函数,初始化dockerCilent
    DockerUtils(){
    
    
        dockerClient = DockerClientBuilder.getInstance(DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("tcp://x.x.x.x:2375").build()).build();
    }
    // 或直接如下写法,这个版本如下方法已被弃用,不推荐,但是可以用
    /*
    DockerUtils(){
        dockerClient = DockerClientBuilder.getInstance("tcp://x.x.x.x:2375").build();
    }
    */
    // region 编写操作Docker的方法
    ...
    // endregion
}

Next is the method of operating Docker. In order to be more intuitive, it will not be written together, just write it in the region block

create container

/**
 * 创建容器
 * @param iamgeName 镜像名称
 * @param portMap 端口映射Map,key是hostPort,value是containerPort
 * @return 创建完的容器
 */
public CreateContainerResponse createCon(String iamgeName, Map<String,Port> portMap) {
    
    
    // 创建容器需要使用的命令
    CreateContainerCmd ccm = dockerClient.createContainerCmd(iamgeName);
    // 封装端口映射
    List<PortBinding> list = new ArrayList<>();
    for (String hostPort : portMap.keySet()) {
    
    
        // 暴露端口
        ccm = ccm.withExposedPorts(ExposedPort.parse(portMap.get(hostPort) + "/tcp"));
        // 绑定主机端⼝ -> docker容器端⼝
        list.add(PortBinding.parse(hostPort + ":" + portMap.get(hostPort)));
    }
    HostConfig hostConfig = HostConfig.newHostConfig()
            .withPortBindings(list);
    // 执行创建命令
    CreateContainerResponse container = ccm
            .withHostConfig(hostConfig)
            .exec();

    return container;
}

Basic container operations

/**
 * 开启容器
 * @param id 容器ID
 */
public void startCon(String id) {
    
    
    dockerClient.startContainerCmd(id).exec();
}

/**
 * 关闭容器
 * @param id 容器ID
 */
public void stopCon(String id) {
    
    
    dockerClient.stopContainerCmd(id).exec();
}

/**
 * 暂停容器
 * @param id 容器ID
 */
public void pauseCon(String id) {
    
    
    dockerClient.pauseContainerCmd(id).exec();
}

/**
 * 重启容器
 * @param id 容器ID
 */
public void restartCon(String id) {
    
    
    dockerClient.restartContainerCmd(id).exec();
}

delete container

/**
 * 删除容器
 * @param id 容器ID
 */
public void startCon(String id) {
    
    
    // 删除之前请先调用关闭方法关闭容器!!!!!
    DockerClient dockerClientByIp = DockerClientBuilder.getInstance("tcp://" + hostip + ":2375").build();
    dockerClientByIp.startContainerCmd(id).exec();
}

Save the container as an image

/**
* docker容器commit为镜像
* @param containerID 容器id
* @param rep 镜像的仓库,就相当于【ubuntu:latest】中的【ubuntu】
* @param tag 镜像的标签,就相当于【ubuntu:latest】中的【latest】
* @return
*/
public void createImageByContainer(String containerID, String rep, String tag)  throws Exception{
    
    
    dockerClientByIp.commitCmd(containerID).withRepository(rep).withTag(tag).exec();
}

Full code giveaway

After writing this, I am afraid that some people will not know how to write it completely, so I will write it out.

public class DockerUtils {
    
    
    // 定义dockerClient操作docker
    private DockerClient dockerClient;
    // 重新定义无参构造函数,初始化dockerCilent
    DockerUtils(){
    
    
        dockerClient = DockerClientBuilder.getInstance(DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("tcp://x.x.x.x:2375").build()).build();
    }
    // 或直接如下写法,这个版本如下方法已被弃用,不推荐,但是可以用
    /*
    DockerUtils(){
        dockerClient = DockerClientBuilder.getInstance("tcp://x.x.x.x:2375").build();
    }
    */
    /**
     * 创建容器
     * @param iamgeName 镜像名称
     * @param portMap 端口映射Map,key是hostPort,value是containerPort
     * @return 创建完的容器
     */
    public CreateContainerResponse createCon(String iamgeName, Map<String,Port> portMap) {
    
    
        // 创建容器需要使用的命令
        CreateContainerCmd ccm = dockerClient.createContainerCmd(iamgeName);
        // 封装端口映射
        List<PortBinding> list = new ArrayList<>();
        for (String hostPort : portMap.keySet()) {
    
    
            // 暴露端口
            ccm = ccm.withExposedPorts(ExposedPort.parse(portMap.get(hostPort) + "/tcp"));
            // 绑定主机端⼝ -> docker容器端⼝
            list.add(PortBinding.parse(hostPort + ":" + portMap.get(hostPort)));
        }
        HostConfig hostConfig = HostConfig.newHostConfig()
                .withPortBindings(list);
        // 执行创建命令
        CreateContainerResponse container = ccm
                .withHostConfig(hostConfig)
                .exec();
    
        return container;
    }
    /**
     * 开启容器
     * @param id 容器ID
     */
    public void startCon(String id) {
    
    
        dockerClient.startContainerCmd(id).exec();
    }
    
    /**
     * 关闭容器
     * @param id 容器ID
     */
    public void stopCon(String id) {
    
    
        dockerClient.stopContainerCmd(id).exec();
    }
    
    /**
     * 暂停容器
     * @param id 容器ID
     */
    public void pauseCon(String id) {
    
    
        dockerClient.pauseContainerCmd(id).exec();
    }
    
    /**
     * 重启容器
     * @param id 容器ID
     */
    public void restartCon(String id) {
    
    
        dockerClient.restartContainerCmd(id).exec();
    }
    /**
     * 删除容器
     * @param id 容器ID
     */
    public void startCon(String id) {
    
    
        // 删除之前请先调用关闭方法关闭容器!!!!!
        DockerClient dockerClientByIp = DockerClientBuilder.getInstance("tcp://" + hostip + ":2375").build();
        dockerClientByIp.startContainerCmd(id).exec();
    }/**
    * docker容器commit为镜像
    * @param containerID 容器id
    * @param rep 镜像的仓库,就相当于【ubuntu:latest】中的【ubuntu】
    * @param tag 镜像的标签,就相当于【ubuntu:latest】中的【latest】
    * @return
    */
    public void createImageByContainer(String containerID, String rep, String tag)  throws Exception{
    
    
        dockerClientByIp.commitCmd(containerID).withRepository(rep).withTag(tag).exec();
    }
}

epilogue

There are many operations in the Api. After studying the basic operations, it is estimated that the others will be integrated. Let’s match them according to the needs.

Guess you like

Origin blog.csdn.net/u012751272/article/details/125404979