写一段java docker client_Java 操作 Docker 使用 java 执行 Docker run 内部命令的代码
时间: 2024-05-08 13:17:36 浏览: 167
以下是一段Java Docker Client代码,可以使用Java操作Docker并执行Docker run内部命令:
```java
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.HostConfig;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
public class DockerClientExample {
public static void main(String[] args) {
// 创建DockerClient
DockerClient dockerClient = DockerClientBuilder.getInstance().build();
// 配置端口映射
ExposedPort tcp80 = ExposedPort.tcp(80);
PortBinding portBinding = new PortBinding(PortBinding.parse("80"), ExposedPort.parse("80"));
HostConfig hostConfig = HostConfig.newHostConfig().withPortBindings(portBinding);
// 创建容器
CreateContainerResponse container = dockerClient.createContainerCmd("nginx:latest")
.withHostConfig(hostConfig)
.withExposedPorts(tcp80)
.withName("my-nginx")
.exec();
// 启动容器
dockerClient.startContainerCmd(container.getId()).exec();
// 执行Docker run内部命令
dockerClient.execCreateCmd(container.getId())
.withCmd("echo", "Hello World")
.exec(new ExecStartResultCallback());
// 停止容器
dockerClient.stopContainerCmd(container.getId()).exec();
// 删除容器
dockerClient.removeContainerCmd(container.getId()).exec();
}
}
```
阅读全文