问题描述
我尝试在我的Java代码上获取docker容器的详细信息,并成功获取它.但是我需要获得CPU& Docker容器的内存使用情况.在终端本身中,我们可以使用 docker stats 检查状态.但是我的问题是如何在Java代码中获取Docker容器的统计信息?
I try to get docker container details on my java code and successfully can get it. But I need to get the CPU & memory usage of Docker container.In the terminal itself, we can check the status with docker stats .But my question is how to get the stats of Docker container in java code?
推荐答案
回答得有点晚,但可能会对某人有所帮助.
A bit late for answering but it may help somebody.
考虑到您的主机上正在运行Docker引擎,您可以对Docker API端点进行RESTful调用以获取各种响应,请参见此处的Docker API端点.
Considering you are running Docker engine on your host, you can make RESTful calls to Docker API endpoints to get various responses, see list of Docker API endpoints here.
现在要获取特定容器的内存和CPU使用率(以及更多),可以调用http://localhost:2375/containers/some-containerId/stats?stream=0
API端点.
Now to get memory and CPU usage (and much more) of a specific container you can call http://localhost:2375/containers/some-containerId/stats?stream=0
API endpoint.
在浏览器中访问此链接并查看响应,有关Java的信息,请参见下文-
Go access this link on a browser and see the response, for Java see below -
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;
@RestController
public class DockerController {
@GetMapping("/getStats/{containerId}")
public String getStats(@PathVariable String containerId){
String statistics = null;
RestTemplate restTemplate = new RestTemplate();
statistics = restTemplate.getForObject("http://localhost:2375/containers/"+containerId+"/stats?stream=0", String.class);
if(statistics != null){
System.out.println("Container statistics - \n" + statistics);
}
return statistics;
}
}
在这里,我以String
的形式获取统计信息,也可以以HashMap
的形式获取它.
Here I'm getting statistics as a String
, you can also get it as a HashMap
.
上述方法的输出将类似于在浏览器http://localhost:2375/containers/some-containerId/stats?stream=0
The output of the above method will be similar to what you would get if you fired this link on the browser http://localhost:2375/containers/some-containerId/stats?stream=0
希望这会有所帮助!
这篇关于如何在Java代码中获取Docker统计信息的详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!