写一段java操作docker创建以及销毁的代码
时间: 2023-05-12 19:07:12 浏览: 106
好的,以下是一段Java代码,可以用来操作Docker创建和销毁容器:
```
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.PullImageResultCallback;
public class DockerManager {
private DockerClient dockerClient;
public DockerManager() {
dockerClient = DockerClientBuilder.getInstance().build();
}
public void createContainer(String imageName, String containerName, int hostPort, int containerPort) {
dockerClient.pullImageCmd(imageName).exec(new PullImageResultCallback()).awaitSuccess();
ExposedPort tcp = ExposedPort.tcp(containerPort);
PortBinding binding = new PortBinding(Ports.Binding.bindPort(hostPort), tcp);
CreateContainerResponse container = dockerClient.createContainerCmd(imageName)
.withName(containerName)
.withExposedPorts(tcp)
.withHostConfig(new HostConfig().withPortBindings(binding))
.exec();
dockerClient.startContainerCmd(container.getId()).exec();
}
public void destroyContainer(String containerName) {
dockerClient.stopContainerCmd(containerName).exec();
dockerClient.removeContainerCmd(containerName).exec();
}
}
```
这段代码使用了Docker Java API来创建和销毁容器。在创建容器时,需要指定镜像名称、容器名称、主机端口和容器端口。在销毁容器时,只需要指定容器名称即可。
阅读全文