当前位置: 首页 > 工具软件 > docker-client > 使用案例 >

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

钮晟
2023-12-01

开启Docker远程访问

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

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


        <!-- docker java -->
        <dependency>
            <groupId>com.github.docker-java</groupId>
            <artifactId>docker-java</artifactId>
            <version>3.2.13</version>
        </dependency>

        <!-- docker java httpclient -->
        <dependency>
            <groupId>com.github.docker-java</groupId>
            <artifactId>docker-java-transport-httpclient5</artifactId>
            <version>3.2.13</version>
        </dependency>

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

☘️连接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;
    }

额外的一些配置

  • 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;
        }
    }

☘️查看镜像信息


    /**
     * 查看镜像详细信息
     *
     * @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);
    }

☘️删除镜像


    /**
     * 删除镜像
     *
     * @param client
     * @param imageName
     */
    public void removeImage(DockerClient client, String imageName) {
        client.removeImageCmd(imageName).exec();
    }

☘️构建镜像

    /**
     * 构建镜像
     *
     * @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;
    }

☘️给镜像打tag

    /**
     * 给镜像打tag
     * @param client
     * @param dockerProp
     */
    public void tagImage(DockerClient client, DockerProp dockerProp) {
        client.tagImageCmd(dockerProp.getImageName(), dockerProp.getRespository(), dockerProp.getTag()).exec();
    }

☘️加载镜像文件


    /**
     * 加载镜像文件
     *
     * @param client
     * @param inputStream
     */
    public static void loadImage(DockerClient client, InputStream inputStream) {
        client.loadImageCmd(inputStream).exec();
    }

☘️获取镜像列表

    /**
     * 获取镜像列表
     *
     * @param client
     * @return
     */
    public List<Image> imageList(DockerClient client) {
        List<Image> imageList = client.listImagesCmd().withShowAll(true).exec();
        return imageList;
    }

☘️创建容器

/**
     * 创建容器
     *
     * @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;
    }

☘️启动容器


    /**
     * 启动容器
     *
     * @param client
     * @param containerId
     */
    public void startContainer(DockerClient client, String containerId) {
        client.startContainerCmd(containerId).exec();
    }

☘️停止容器


    /**
     * 停止容器
     *
     * @param client
     * @param containerId
     */
    public void stopContainer(DockerClient client, String containerId) {
        client.stopContainerCmd(containerId).exec();
    }

☘️删除容器

    /**
     * 删除容器
     *
     * @param client
     * @param containerId
     */
    public void removeContainer(DockerClient client, String containerId) {
        client.removeContainerCmd(containerId).exec();
    }

部分代码未展示,全部代码请点击源码查看源码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配置网络,主机互通,可上网

 类似资料: