I am creating a instance of my image like
docker run -P webmodule-xy
The Dockerfile for the webmodule exposes a port (e.g. 8080).
My goal now is to obtain the mapped / assigned port number which is accessible from the outside via Java. Is there a environment variable or something like that?
Usecase: The webmodule-xy should register itself on another web-application and provide its IP + Port so the other application can contact the webmodule-xy later on. IP is no problem, but the port is.
I already found this open issue on GitHub, but I can't believe that there is no simple solution. Like stated there, REST is not an option:
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.
Once the container is running, you should be able to use docker inspect
in order to get the port number mapped on the host by the -P
option.
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.
As detailed in "Docker, how to get container information from within the container?", you can:
use the 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
would, after the docker run
, add the port read from docker inspect
as an environment variable and run the java app (issue 8838 ):
docker exec -i CONTAINER_ID /bin/bash -c "export PORT=<port> && run_java-app"
The java app (from within the container) would read the environment variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With