如何使用docker-java获取容器的主机名?

huangapple go评论97阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2020年10月23日 21:13:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64500735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定