<dependency> <groupId>com.github.docker-java</groupId> <artifactId>docker-java</artifactId> <version>3.2.5</version> </dependency>创建Docker客户端
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()方法设置了Docker守护进程的连接地址,withDockerCertPath()方法设置了TLS证书的路径,withApiVersion()方法设置了Docker API的版本。最后,通过调用build()方法构建了一个DockerClient对象。DockerClientBuilder类是用于构建和配置DockerClient对象的构建器类。它提供了一组方法,用于设置与Docker守护进程通信所需的参数和配置。
import com.github.dockerjava.api.command.BuildImageResultCallback; String dockerfilePath = "/path/to/dockerfile"; String imageName = "my-image"; String imageTag = "latest"; // 堆代码 duidaima.com dockerClient.buildImageCmd() .withDockerfile(new File(dockerfilePath)) .withTags(Collections.singleton(imageName + ":" + imageTag)) .exec(new BuildImageResultCallback()) .awaitCompletion();withDockerfile(new File(dockerfilePath)):指定Dockerfile的路径,用于构建镜像。
withProgressHandler(progressHandler):设置用于处理构建镜像进度的ProgressHandler。
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();在上述代码中,imageName表示要使用的镜像的名称,containerName表示要创建的容器的名称。hostPort和containerPort分别表示主机端口和容器端口,用于进行端口映射。volumeHostPath和volumeContainerPath表示主机路径和容器路径,用于挂载卷。其中,CreateContainerResponse对象,包含了有关新创建容器的信息,比如容器的ID、名称等。以便接下来的启动停止容器等操作。
dockerClient.startContainerCmd(container.getId()).exec();停止和删除容器
dockerClient.stopContainerCmd(container.getId()).exec(); dockerClient.removeContainerCmd(container.getId()).exec();在上述代码中,container.getId()获取到的是容器的ID。