英文:
How can I get the hostname of a container using docker-java?
问题
我可以这样创建、启动和获取 Docker 容器实例:
CreateContainerResponse response = dockerClient.createContainerCmd(imageId).exec();
String containerId = response.getId();
dockerClient.startContainerCmd(containerId).exec();
Container container = dockerClient.listContainersCmd()
.withIdFilter(Collections.singletonList(containerId))
.exec()
.get(0);
然而,Container
对象似乎没有暴露主机名。
我也可以这样检查正在运行的容器:
InspectContainerResponse response = dockerClient.inspectContainerCmd(container.getId()).exec();
同样,响应中没有包含主机名。它确实包含一个 hostnamePath
,该路径引用一个文件,文件中存储了主机名,但是读取这个文件需要 root 权限,而我的应用程序没有这个权限。
我可以从容器 ID 中提取主机名,但这似乎不够稳定。我也想避免在不必要的情况下调用外部的 Docker 进程。
有没有办法可以直接从 docker-java 中获取主机名呢?
英文:
I can create, start and retrieve an instance of a docker container like this:
CreateContainerResponse response = dockerClient.createContainerCmd(imageId).exec();
String containerId = response.getId();
dockerClient.startContainerCmd(containerId).exec()
Container container = dockerClient.listContainersCmd()
.withIdFilter(Collections.singletonList(containerId))
.exec()
.get(0);
However, the Container
object does not appear to expose the hostname.
I can also inspect a running container like this:
InspectContainerResponse response = dockerClient.inspectContainerCmd(container.getId()).exec()
Again, the response doesn't contain the hostname. It does contain a hostnamePath which references a file where the hostname is stored but this requires root privileges to read which my app won't have.
I could substring the container id but this seems quite brittle. I'd also like to avoid shelling out to the external docker process if I don't have to.
Is there any way I can retrieve the hostname directly from docker-java?
答案1
得分: 1
dockerClient.inspectContainerCmd(container.getId()).exec().getConfig().getHostName();
英文:
dockerClient.inspectContainerCmd(container.getId()).exec().getConfig().getHostName();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论