How to create a Docker container in Java?

To create a Docker container in Java, you need to use the Docker Java API library. Here is a simple example code:

  1. Firstly, make sure to add the dependency of the Docker Java API library in the pom.xml file of the project.
<dependencies>
  <dependency>
    <groupId>com.github.docker-java</groupId>
    <artifactId>docker-java</artifactId>
    <version>3.2.10</version>
  </dependency>
</dependencies>
  1. Create a Java class and import the necessary Docker Java API library.
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.PullImageResultCallback;

public class DockerContainerCreator {

    public static void main(String[] args) {
        // 创建Docker客户端
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        // 从Docker镜像仓库中拉取一个镜像
        dockerClient.pullImageCmd("image:tag")
                .exec(new PullImageResultCallback())
                .awaitSuccess();

        // 创建一个容器
        CreateContainerResponse container = dockerClient.createContainerCmd("image:tag")
                .withCmd("command")
                .exec();

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

In this example, we are using DockerClientBuilder to create a DockerClient object, then pulling an image from the Docker image repository using the pullImageCmd method. Next, we create a container using the createContainerCmd method and set the container’s command using the withCmd method. Finally, we start the container using the startContainerCmd method.

Please note that this is just a simple example code, in actual usage we need to handle exceptions, set other properties of the container, etc.

bannerAds