文章目录
- dokcer-java使用
- xml
- ping
- 拉取镜像
- 创建容器
- 查看所有容器信息
- 启动容器
- 查看日志
- 删除容器
- 删除镜像
dokcer-java使用
xml
引入依赖
<!-- https://mvnrepository.com/artifact/com.github.docker-java/docker-java -->
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.docker-java/docker-java-transport-httpclient5 -->
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java-transport-httpclient5</artifactId>
<version>3.3.0</version>
</dependency>
ping
DockerClient dockerClient = DockerClientBuilder.getInstance().build();
PingCmd pingCmd = dockerClient.pingCmd();
pingCmd.exec();
拉取镜像
这里拉取nginx
public class dockerDemo {
public static void main(String[] args) throws InterruptedException {
// 初始参数docker
DockerClient dockerClient = DockerClientBuilder.getInstance().build();
String image = "nginx:latest";
PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
@Override
public void onNext(PullResponseItem item) {
System.out.println("下载镜像状态:" + item.getStatus());
super.onNext(item);
}
};
pullImageCmd.
exec(pullImageResultCallback)
.awaitCompletion(); // 等待下载完成,不然一直阻塞
System.out.println("下载完成");
}
}
创建容器
String image = "nginx:latest";
// 创建容器
CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
CreateContainerResponse createContainerResponse = containerCmd.
withCmd("echo", "hello Docker") // 启动时自动执行的命令
.exec();
System.out.println(createContainerResponse);
查看所有容器信息
// 获取所有容器
ListContainersCmd listContainersCmd = dockerClient.listContainersCmd(); // 获取容器列表命令
List<Container> containers = listContainersCmd.withShowAll(true).exec(); // 执行,包含未启动的容器
for (Container container : containers) {
System.out.println(container);
}
String containId = createContainerResponse.getId(); // 获取容器id
启动容器
DockerClient dockerClient = DockerClientBuilder.getInstance().build();
dockerClient.startContainerCmd(containId).exec(); // 启动容器
查看日志
注意操作是异步的,等待完成。
// 查看日志
// 回调函数
LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback(){
@Override
public void onNext(Frame item) {
System.out.println("日志" + new String(item.getPayload()));
super.onNext(item);
}
};
ResultCallback<Frame> exec = dockerClient.logContainerCmd(containId)
.withStdErr(true) // 打开错误输出
.withStdOut(true) // 打开标准输出
.exec(logContainerResultCallback)
.awaitCompletion(); // 因为是异步的,一定要等待完成,因为是异步的,可能还没查看日志就结束程序了
删除容器
// 删除容器
dockerClient.removeContainerCmd(containId).exec();
dockerClient.removeImageCmd(containId).withForce(true).exec(); //强转删除
// 删除镜像
dockerClient.removeImageCmd(image).exec();
删除镜像
dockerClient.removeImageCmd(image).exec();