Docker Client (another java docker client api)

The previous article mentioned docker Java. Here is another docker client library, docker client

Version compatible

Compatible with 17.03 1~ce - 17.12. 1 ~ Ce (click [here] [1] to view)

Download jar package

Click [via Maven] [Maven search] to search and download the latest jar package

pom. The XML configuration is as follows:

<dependency>
  <groupId>com.spotify</groupId>
  <artifactId>docker-client</artifactId>
  <version>LATEST-VERSION</version>
</dependency>

The latest is 8.15 0

<dependency>
	<groupId>com.spotify</groupId>
	<artifactId>docker-client</artifactId>
	<version>8.15.0</version>
</dependency>

Use examples

// Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars
final DockerClient docker = DefaultDockerClient.fromEnv().build();

// Pull an image
docker.pull("busy@R_784_2419@");

// Bind container ports to host ports
final String[] ports = {"80","22"};
final Map<String,List<PortBinding>> portBindings = new HashMap<>();
for (String port : ports) {
    List<PortBinding> hostPorts = new ArrayList<>();
    hostPorts.add(PortBinding.of("0.0.0.0",port));
    portBindings.put(port,hostPorts);
}

// Bind container port 443 to an automatically allocated available host port.
List<PortBinding> randomPort = new ArrayList<>();
randomPort.add(PortBinding.randomPort("0.0.0.0"));
portBindings.put("443",randomPort);

final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();

// Create container with exposed ports
final ContainerConfig containerConfig = ContainerConfig.builder()
    .hostConfig(hostConfig)
    .image("busy@R_784_2419@").exposedPorts(ports)
    .cmd("sh","-c","while :; do sleep 1; done")
    .build();

final ContainerCreation creation = docker.createContainer(containerConfig);
final String id = creation.id();

// Inspect container
final ContainerInfo info = docker.inspectContainer(id);

// Start container
docker.startContainer(id);

// Exec command inside running container with attached STDOUT and STDERR
final String[] command = {"sh","ls"};
final ExecCreation execCreation = docker.execCreate(
    id,command,DockerClient.ExecCreateParam.attachStdout(),DockerClient.ExecCreateParam.attachStderr());
final LogStream output = docker.execStart(execCreation.id());
final String execOutput = output.readFully();

// Kill container
docker.killContainer(id);

// Remove container
docker.removeContainer(id);

// Close the docker client
docker.close();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>