A brief discussion on operating Docker using Java API

background:

Docker can be easily operated in Java using the com.github.docker-java library. Below is a detailed tutorial that includes the steps to create an image, create a container, start a container, stop a container, and delete a container with instructions for each step.

premise:

First, add the dependency of com.github.docker-java library to your Java project. You can add the following dependencies in the configuration file of your build tool (such as Maven or Gradle):

<dependency>

    <groupId>com.github.docker-java</groupId>

    <artifactId>docker-java</artifactId>

    <version>3.2.5</version>

</dependency>

Create Docker client

import com.github.dockerjava.api.DockerClient;

import com.github.dockerjava.api.DockerClientBuilder;

DockerClient dockerClient = DockerClientBuilder.getInstance()

        .withDockerHost("tcp://localhost:2375")

        .withDockerCertPath("/path/to/cert")

        .withApiVersion("1.41")

        .build();

withDockerHost()The connection address of the Docker daemon is set by the method, withDockerCertPath()the path of the TLS certificate is set by the method, and withApiVersion()the version of the Docker API is set by the method. Finally, build()an object is constructed by calling methods DockerClient.

  1. DockerClientBuilderDockerClientClasses are builder classes used to build and configure objects. It provides a set of methods for setting the parameters and configuration required to communicate with the Docker daemon.

  2. getInstance()Is DockerClientBuildera static method of the class. By calling this method, you can obtain DockerClientBuilderthe singleton instance.

  3. DockerClientBuilderThe design using singleton mode is mainly to provide a global shared instance with access to the Docker daemon. This avoids repeated creation and destruction DockerClientBuilderof instances, improving performance and efficiency.

  4. After using the instance DockerClientBuilder.getInstance()obtained by the method DockerClientBuilder, you can make chain calls through the instance and set various parameters and configurations related to Docker daemon communication.

  5. Through the chain call DockerClientBuildermethod, you can set, for example, the connection address, authentication information, timeout, TLS configuration, etc. of the Docker daemon. These methods include withDockerHost(), withDockerCertPath(), withDockerConfig(), withApiVersion()etc.

  6. Finally, by calling build()methods, an object can be constructed DockerClientfor interacting with the Docker daemon. This object can perform various Docker operations, such as creating containers, starting containers, building images, etc.

Create image

import com.github.dockerjava.api.command.BuildImageResultCallback;

String dockerfilePath = "/path/to/dockerfile";

String imageName = "my-image";

String imageTag = "latest";

dockerClient.buildImageCmd()

    .withDockerfile(new File(dockerfilePath))

    .withTags(Collections.singleton(imageName + ":" + imageTag))

    .exec(new BuildImageResultCallback())

    .awaitCompletion();

  • withDockerfile(new File(dockerfilePath)): Specify the path of the Dockerfile for building the image.
  • withTags(Collections.singleton(imageName + ":" + imageTag)): Specify the label of the image. withTagsYou can pass a collection containing mirror tags through the method. Here, Collections.singleton()the method is used to create a collection containing only one element. 
  • withBaseDirectory(baseDirectory): Set the base directory, which contains all the files needed to build the image. When used together with withDockerfile()Dockerfile in the base directory is automatically associated into the build command.
  • withNoCache(): Disable cache and re-execute all commands every time you build an image, ensuring the latest files and dependencies are used.
  • withPull(pull): Specifies whether the latest base image should be pulled before building. The default falseis not to pull.
  • withQuiet(): Set silent mode and do not output the log information of building the image.
  • withBuildArg(buildArg): Set build parameters using Map<String, String>type parameters. Key-value pairs represent the names and values ​​of build parameters.
  • withLabels(labels): Use Map<String, String>type parameters to set the label of the image. Key-value pairs represent the key and value of a tag.
  • withBuildArgs(buildArgs): Set build parameters using Map<String, String>type parameters. Similar to withBuildArg(), but you can set multiple build parameters at once.
  • withPull(): Set whether the latest base image should be pulled before building.
  • withProgressHandler(progressHandler): Set to handle the progress of building the image ProgressHandler.

Create container

import com.github.dockerjava.api.command.CreateContainerResponse;

import com.github.dockerjava.api.model.Bind;

import com.github.dockerjava.api.model.PortBinding;

import com.github.dockerjava.api.model.Volume;

String imageName = "my-image";

String containerName = "my-container";

int hostPort = 8080;

int containerPort = 80;

String volumeHostPath = "/host/path";

String volumeContainerPath = "/container/path";

CreateContainerResponse container = dockerClient.createContainerCmd(imageName)

    .withName(containerName)

    .withPortBindings(new PortBinding(

        new Binding(null, null, hostPort),

        new ExposedPort(containerPort)))

    .withBinds(new Bind(volumeHostPath, new Volume(volumeContainerPath)))

    .exec();

In the above code, imageNamerepresents the name of the image to be used and containerNamethe name of the container to be created. hostPortand containerPortrepresent the host port and container port respectively, used for port mapping. volumeHostPathand volumeContainerPathrepresent the host path and container path, used to mount the volume. Among them, CreateContainerResponsethe object contains information about the newly created container, such as the ID and name of the container. for subsequent operations such as starting and stopping the container.

  • withName(containerName): Specify a name for the container.
  • withPortBindings(portBindings):Specify the port binding of the container. portBindingsIs an PortBindingobject used to map host ports to ports within the container.
  • withBinds(bindings): Specifies the volume binding of the container. bindingsIs an Bindobject used to mount the host's directory or volume to a path within the container.

Start container

1

dockerClient.startContainerCmd(container.getId()).exec();

Stop and delete containers

dockerClient.stopContainerCmd(container.getId()).exec();

dockerClient.removeContainerCmd(container.getId()).exec();

In the above code, container.getId()what is obtained is the ID of the container.

Finally, I would like to thank everyone who reads my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it directly:

This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!

Guess you like

Origin blog.csdn.net/NHB456789/article/details/135244592