• docker-java 用Java操作docker创建容器并运行运行容器


    🍀开启Docker远程访问

    参考上一篇文章:Docker设置开启远程访问

    🍀创建项目并引入docker-java依赖

    
            <!-- docker java -->
            
                com.github.docker-java</groupId>
                docker-java</artifactId>
                3.2.13</version>
            </dependency>
    
            <!-- docker java httpclient -->
            
                com.github.docker-java</groupId>
                docker-java-transport-httpclient5</artifactId>
                3.2.13</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Apache HttpClient 5介绍:

    This transport is based on Apache HttpClient library version 5, which has a great flexibility and allows us to implement all Docker-specific features and protocols required, without having to use internal APIs or anything.
    It has everything to become the default transport of docker-java in future releases.

    Apache HttpClient 5基于Apache HttpClient库实现,具有很大的灵活性,我们无需使用docker内部API,就可以实现所有Docker特定功能和协议。并且在未来的版本中,它将成为docker java的默认传输工具。

    除Apache HttpClient 5以外,还可以使用Zerodep、OkHttp、Jersey和Netty实现docker的连接传输。

    docker的一些配置选项

    访问docker的配置

    docker:
      host: tcp://192.168.1.17:2375
      api-version: 1.41
    
    
    • 1
    • 2
    • 3
    • 4

    ☘️连接docker

    import com.github.dockerjava.core.DockerClientConfig
    import com.github.dockerjava.core.DefaultDockerClientConfig
    
    
        /**
         * 连接docker服务器
         *
         * @return
         */
        public DockerClient connect() {
            // 配置docker CLI的一些选项
            DefaultDockerClientConfig config = DefaultDockerClientConfig
                    .createDefaultConfigBuilder()
                    .withDockerTlsVerify(DOCKER_TLS_VERIFY)
                    .withDockerHost(HOST)
                    // 与docker版本对应,参考https://docs.docker.com/engine/api/#api-version-matrix
                    // 或者通过docker version指令查看api version
                    .withApiVersion(API_VERSION)
                    .withRegistryUrl(REGISTRY_URL)
                    .build();
    
            // 创建DockerHttpClient
            DockerHttpClient httpClient = new ApacheDockerHttpClient
                    .Builder()
                    .dockerHost(config.getDockerHost())
                    .maxConnections(100)
                    .connectionTimeout(Duration.ofSeconds(30))
                    .responseTimeout(Duration.ofSeconds(45))
                    .build();
    
            DockerClient dockerClient = DockerClientImpl.getInstance(config, httpClient);
            Info info = dockerClient.infoCmd().exec();
            String infoStr = JSONObject.toJSONString(info);
            System.out.println("docker环境信息");
            System.out.println(infoStr);
            return dockerClient;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    额外的一些配置

    • DOCKER_HOST Docker的地址,比如: tcp://localhost:2376 或者unix:///var/run/docker.sock
    • DOCKER_TLS_VERIFY 是否开启 TLS 验证 (httphttps 之间切换)
    • DOCKER_CERT_PATH TLS 验证的证书路径
    • DOCKER_CONFIG 其他docker配置文件的路径 (比如 .dockercfg)
    • api.version API version版本
    • registry.url 下载源地址(docker镜像存放的地址)
    • registry.username 登陆用户名 (推送镜像到docker云仓库时需要)
    • registry.password 登陆用户密码(推送镜像到docker云仓库时需要)
    • registry.email 登陆账户的邮箱(推送镜像到docker云仓库时需要)

    ☘️拉取镜像

    
        /**
         * 拉取镜像
         *
         * @param client
         * @param imageName
         * @return
         * @throws InterruptedException
         */
        public boolean pullImage(DockerClient client, String imageName) {
            boolean isSuccess = false;
            try {
                isSuccess = client.pullImageCmd(imageName)
                        .start()
                        .awaitCompletion(30, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                return isSuccess;
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    ☘️查看镜像信息

    
        /**
         * 查看镜像详细信息
         *
         * @param client
         * @param imageName
         * @return
         */
        public String inspectImage(DockerClient client, String imageName) {
            InspectImageResponse response = client.inspectImageCmd(imageName).exec();
            System.out.println(response.toString());
            System.out.println(JSONObject.toJSONString(response));
            return JSONObject.toJSONString(response);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    ☘️删除镜像

    
        /**
         * 删除镜像
         *
         * @param client
         * @param imageName
         */
        public void removeImage(DockerClient client, String imageName) {
            client.removeImageCmd(imageName).exec();
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ☘️构建镜像

        /**
         * 构建镜像
         *
         * @param client
         * @param dockerProp
         * @return
         */
        public String buildImage(DockerClient client, DockerProp dockerProp) {
            ImmutableSet<String> tag = ImmutableSet.of(dockerProp.getImageName() + ":" + dockerProp.getImageTag());
            String imageId = client.buildImageCmd(new File(dockerProp.getDockerfilePath()))
                    .withTags(tag)
                    .start()
                    .awaitImageId();
            return imageId;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    ☘️给镜像打tag

        /**
         * 给镜像打tag
         * @param client
         * @param dockerProp
         */
        public void tagImage(DockerClient client, DockerProp dockerProp) {
            client.tagImageCmd(dockerProp.getImageName(), dockerProp.getRespository(), dockerProp.getTag()).exec();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    ☘️加载镜像文件

    
        /**
         * 加载镜像文件
         *
         * @param client
         * @param inputStream
         */
        public static void loadImage(DockerClient client, InputStream inputStream) {
            client.loadImageCmd(inputStream).exec();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    ☘️获取镜像列表

        /**
         * 获取镜像列表
         *
         * @param client
         * @return
         */
        public List<Image> imageList(DockerClient client) {
            List<Image> imageList = client.listImagesCmd().withShowAll(true).exec();
            return imageList;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    ☘️创建容器

    /**
         * 创建容器
         *
         * @param client
         * @return
         */
        public CreateContainerResponse createContainers(DockerClient client, DockerProp dockerProp) {
            // 端口绑定
            Map<Integer, Integer> portMap = Optional.ofNullable(dockerProp).map(DockerProp::getPartMap).orElse(new HashMap<>());
            Iterator<Map.Entry<Integer, Integer>> iterator = portMap.entrySet().iterator();
            List<PortBinding> portBindingList = new ArrayList<>();
            List<ExposedPort> exposedPortList = new ArrayList<>();
            while (iterator.hasNext()) {
                Map.Entry<Integer, Integer> entry = iterator.next();
                ExposedPort tcp = ExposedPort.tcp(entry.getKey());
                Ports.Binding binding = Ports.Binding.bindPort(entry.getValue());
                PortBinding ports = new PortBinding(binding, tcp);
                portBindingList.add(ports);
                exposedPortList.add(tcp);
            }
    
            CreateContainerResponse container = client.createContainerCmd(dockerProp.getImageName())
                    .withName(dockerProp.getContainerName())
                    .withHostConfig(newHostConfig().withPortBindings(portBindingList))
                    .withExposedPorts(exposedPortList).exec();
    
            return container;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    ☘️启动容器

    
        /**
         * 启动容器
         *
         * @param client
         * @param containerId
         */
        public void startContainer(DockerClient client, String containerId) {
            client.startContainerCmd(containerId).exec();
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ☘️停止容器

    
        /**
         * 停止容器
         *
         * @param client
         * @param containerId
         */
        public void stopContainer(DockerClient client, String containerId) {
            client.stopContainerCmd(containerId).exec();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    ☘️删除容器

        /**
         * 删除容器
         *
         * @param client
         * @param containerId
         */
        public void removeContainer(DockerClient client, String containerId) {
            client.removeContainerCmd(containerId).exec();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    部分代码未展示,全部代码请点击源码查看源码https://github.com/BerBai/JavaExample/tree/master/dockerjavademo

    参考
    https://github.com/docker-java/docker-java/blob/master/docs/getting_started.md
    https://docs.docker.com/

    其他系列文章

    docker 安装 与 卸载 centos
    Windows11 安装Docker,安装至D盘(其他非C盘皆可)
    Windows11 Docker镜像存储路径更改(非C盘路径)

    Dockerfile 文件结构、docker镜像构建过程详细介绍
    Dockerfile文件中CMD指令与ENTRYPOINT指令的区别
    构建Docker镜像指南,含实战案例
    Docker 制作自定义化的Tomcat镜像
    docker 安装 mysql 并映射数据库存放路径及配置文件
    docker安装tomcat 映射配置文件、日志文件
    docker安装nginx,配置nginx,并成功访问
    docker安装redis并将配置文件和数据文件映射到外部
    Docker 容器互联 --link 和 自定义网络
    docker 完成 redis集群搭建
    Docker Compose 简介、安装、初步体验
    Docker Compose学习之docker-compose.yml编写规则 及 实战案例
    Docker Compose配置springboot微服务项目
    Docker Swarm 初步认识 及 集群搭建
    Docker设置开启远程访问
    docker-java 用Java操作docker创建容器并运行运行容器

    VMware配置网络,主机互通,可上网

  • 相关阅读:
    RabbitMQ高级篇 笔记
    常见列表字典排序
    使用rustc_interface进行类型检查
    一道数学题,让芯片巨头亏了5亿美金!
    SimpleDateFormat严格限制日期转换setLenient(false)
    Mybatis02动态sql和分页
    Android学习笔记 1.2.5 Gradle插件和java、application等插件 && 1.2.6 依赖管理
    【vue3】踩坑日记,vite与node版本对应(mac环境)
    长胜证券:三大拐点共振 看好智能驾驶新一轮行情
    【SCAU操作系统】期末复习选择题例题解析
  • 原文地址:https://blog.csdn.net/Ber_Bai/article/details/127750221