JAVA调用容器原生API,亲测可用!!!
主要用于容器管理容器,进程管理容器等操作
一、docker-api官方文档
Docker Engine API v1.27 Reference
二、使用curl调用docker-api
curl -v --unix-socket /var/run/docker.sock http:/v1.24/containers/json # -v 打印详情命令
curl -XPOST --unix-socket /var/run/docker.sock http://localhost/containers/ea05b10d8bef/stop
#stop-停止容器 start-启动容器 restart-重启容器
三、使用Java调用docker-api
1.导入依赖
<dependency>
<groupId>com.github.jnr</groupId>
<artifactId>jnr-unixsocket</artifactId>
<version>0.15</version>
</dependency>
2.工具代码
public static boolean execContainerCmd(String containerId, DockerOpsEnum ops) {
try {
File sockFile = new File("/var/run/docker.sock");
UnixSocketAddress address = new UnixSocketAddress(sockFile);
UnixSocketChannel channel = UnixSocketChannel.open(address);
UnixSocket unixSocket = new UnixSocket(channel);
// 调用 Docker API
PrintWriter w = new PrintWriter(unixSocket.getOutputStream());
w.println("POST /containers/" + containerId + "/" + ops.toString() + " HTTP/1.1");
w.println("Host: localhost");
w.println("Accept: */*");
w.println("");
w.flush();
// 关闭 Output,否则会导致下面的 read 操作一直阻塞
unixSocket.shutdownOutput();
// 获取返回结果
BufferedReader br = new BufferedReader(new InputStreamReader(unixSocket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
log.info("执行容器操作数据返回: {}" + line);
}
unixSocket.close();
}catch (Exception e){
log.error("执行容器操作异常: {}", e);
return false;
}
return true;
}
3.说明
DockerOpsEnum为枚举类, 包含对容器的关闭、启动、重启操作
public enum DockerOpsEnum {
stop,
start,
restart;
DockerOpsEnum() {
}
}