java操作dockerapi查看映射端口
时间: 2023-11-16 21:05:04 浏览: 205
可以使用Java的Docker API来查看Docker容器的映射端口。以下是一个简单的Java示例代码:
```java
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import java.util.List;
import java.util.Map;
public class DockerPortMappingExample {
public static void main(String[] args) {
DockerClient dockerClient = DockerClientFactory.createDefault();
List<Container> containers = dockerClient.listContainersCmd().exec();
for (Container container : containers) {
InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
Map<String, List<Map<String, String>>> portBindings = inspectContainerResponse.getHostConfig().getPortBindings();
if (portBindings != null) {
for (Map.Entry<String, List<Map<String, String>>> entry : portBindings.entrySet()) {
String containerPort = entry.getKey();
List<Map<String, String>> hostPorts = entry.getValue();
for (Map<String, String> hostPort : hostPorts) {
String hostIp = hostPort.get("HostIp");
String hostPortNumber = hostPort.get("HostPort");
System.out.println("Container " + container.getId() + " port " + containerPort + " is mapped to " + hostIp + ":" + hostPortNumber);
}
}
}
}
dockerClient.close();
}
}
```
该代码遍历所有Docker容器,并使用`inspectContainerCmd`方法检查每个容器的详细信息。然后,它获取容器的端口映射绑定,遍历它们并打印出每个容器端口映射到的主机IP和端口号。
请注意,要运行此代码,您需要添加以下依赖项到您的Maven项目:
```xml
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java-core</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java-api</artifactId>
<version>3.2.5</version>
</dependency>
```
阅读全文