I want to know which port(s) are exposed when user run the image.

docker run -p 1000:1234 myimagename

I want to get 1234 value in container since I will use it for some configurations(IIS bindings etc.) inside of container.

Is there any env variable for this purpose?


TL;DR: You don't.

From inside of the container, you do not know which ports are exposed since exposing a port is only documentation visible in the image and container metadata. To detect which ports are published, you'd need to know the host IP, which can be difficult to lookup depending on your environment, and then you'd need to do something like a port scan of the host and tcpdump inside the container to detect the incoming request.

All of this is non-trivial because it's solving the problem in the wrong direction. You build your app inside the container to listen on a specific port, configure that default port and potentially let users override it with a variable or config file. Then you document this decision be exposing the port in the Dockerfile with the EXPOSE command. This is only documentation, it goes in the image metadata, users and programs can see it, but by default docker will not do anything with it. Finally, users of your image will publish the port on the host when and where appropriate, and map to the port of your application.

In other words, the right side of the published port (the container port) is largely controlled by the image creator, not the user running the container. If they publish to the wrong port, it is not be the applications responsibility inside the container to dynamically adjust what port it is listening on, and this would be difficult to impossible to do if you had multiple ports anyway.


Please refer the below link You can use docker inspect for the same docker inspect

  • 1
    Hi @Sunil,if I'm not mistaken, this method can be used outside of container(on host machine), what i want to do is getting this value in container.
    – agit
    Dec 12 '18 at 6:48
  • Oh yes, let me try if i can get some info
    – Sunil
    Dec 12 '18 at 8:49

If you want to get the values in the container, You have to have either netcat or telnet or some other tools, to check what are the ports open in your container, and then try to poke that ports from the container to host.

netstat -tnlp will give you all open ports, only if you don't know what are the ports are supposed to have listened in the container nc -zv (host ip) (port) will tell you whether the port is published or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.