Java 操作 Docker

Java 操作 Docker

Administrator 115 2024-09-22

使用 docker-java

开始使用 docker-java ,您至少需要添加两个依赖项:

  • com.github.docker-java:docker-java-core 对于 DockerClient

  • com.github.docker-java:docker-java-transport-* Docker 守护程序通信 参考

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

实例化 DockerClientConfig

DockerClientConfig custom = DefaultDockerClientConfig.createDefaultConfigBuilder()
    .withDockerHost("tcp://docker.somewhere.tld:2376")
    .withDockerTlsVerify(true)
    .withDockerCertPath("/home/user/.docker")
    .withRegistryUsername(registryUser)
    .withRegistryPassword(registryPass)
    .withRegistryEmail(registryMail)
    .withRegistryUrl(registryUrl)
    .build();
  • DOCKER_HOST Docker 主机 URL,例如 tcp://localhost:2376unix:///var/run/docker.sock

  • DOCKER_TLS_VERIFY 启用/禁用 TLS 验证(在 和 https 协议之间切换 http

  • DOCKER_CERT_PATHTLS 验证所需证书的路径

  • DOCKER_CONFIG其他 docker 配置文件(如 .dockercfg)的路径

  • api.version API 版本,例如 1.23

  • registry.url 您的注册表地址。

  • registry.username 您的注册表用户名(推送容器时需要)。

  • registry.password 您的注册表密码。

  • registry.email您的注册表电子邮件。

实例化 DockerHttpClient

DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
    .dockerHost(config.getDockerHost())
    .sslConfig(config.getSSLConfig())
    .maxConnections(100)
    .connectionTimeout(Duration.ofSeconds(30))
    .responseTimeout(Duration.ofSeconds(45))
    .build();

实例化 DockerClient

DockerClient dockerClient = DockerClientImpl.getInstance(config, httpClient);

初始化示例

static final DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost("tcp://localhost:2375")
            .withDockerTlsVerify(false)
            .build();

static final DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
        .dockerHost(config.getDockerHost())
        .sslConfig(config.getSSLConfig())
        .maxConnections(100)
        .connectionTimeout(Duration.ofSeconds(30))
        .responseTimeout(Duration.ofSeconds(45))
        .build();

static final DockerClient dockerClient = DockerClientImpl.getInstance(config, httpClient);

创建 容器

// 创建 docker 容器
CreateContainerResponse response = dockerClient.createContainerCmd("maven-project-demo:latest")
        .withEnv("DEMO_TEXT=docker-list")
        .exec();
logger.info("containerId: {}", response.getId());

// 启动容器
dockerClient.startContainerCmd(response.getId()).exec();