Docker - 在 java 应用程序中获取绑定端口

Docker - Get bound port inside java application

我正在创建我的图像实例,例如

docker run -P webmodule-xy

webmodule 的 Dockerfile 公开了一个端口(例如 8080)。

我现在的目标是获取映射/分配的端口号,该端口号可通过 Java 从外部访问。有没有环境变量之类的?

用例: webmodule-xy 应该在另一个 web 应用程序上注册自己并提供其 IP + 端口,以便其他应用程序稍后可以联系 webmodule-xy。 IP没问题,端口没问题

我已经在 GitHub 上找到了这个 open issue,但我无法相信没有简单的解决方案。如那里所述,REST 不是一个选项:

Allowing a container to have access to the REST API is problematic. For one thing, the REST API is read/write, and if all you need is to read your portmappings, that's a dangerous level of permissions to grant a container just to find out a few ports.

容器 运行ning 后,您应该能够使用 docker inspect 以通过 -P 选项获取主机上映射的端口号。

One can loop over arrays and maps in the results to produce simple text output:

docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' $INSTANCE_ID

Find a Specific Port Mapping

docker inspect --format='{{(index (index .NetworkSettings.Ports "8080/tcp") 0).HostPort}}' $INSTANCE_ID

I now want to get to know this random port inside the java app which runs in the container.

如“Docker, how to get container information from within the container?”中所述,您可以:

  • 通过检查 $HOSTNAME 环境变量找出缩短的 docker id。
  • 使用Docker Remote API

    GET /containers/<docker_id>/json HTTP/1.1
    

Since using Docker Remote API from a container is problematic (because of writable access), you could consider adding the port as a variable environment

  • a docker exec 会在 docker run 之后添加从 docker inspect 读取的端口作为环境变量,并且 运行 添加 java应用程序(issue 8838):

    docker exec -i CONTAINER_ID /bin/bash -c "export PORT=<port> && run_java-app"
    
  • java 应用程序(从容器内)将读取环境变量