<p>TL;DR: You don't.</p>
<p>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.</p>
<p>Instead you should 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 <code>EXPOSE</code> 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.</p>
<p>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 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.</p>
<p>If your application needs to be configured with the publicly reachable port (and probably IP or hostname), that should be injected as a configuration or environment variable. Trying to automate this from inside the container is error prone since your application may be exposed to users through a load balancer or NAT.</p>

CC BY-SA 4.0
2019-06-10T13:15:48.743Z
2022-01-29T20:01:58.337Z
2022-01-29T20:01:58.337Z
BMitch
<p>Tonight I decided to just query the docker api using a small express server running on the host node from within the container.</p>
<pre class="lang-javascript prettyprint-override"><code>const express = require('express')
const app = express()
const port = 3000

var unirest = require('unirest');


app.get('/', (req, res) =&gt; {
    let id = req.query.id;

    if (!req.query.id) {
        res.send('I do not think you belong here.')
    } else {

        var Request = unirest.get('http://localhost:2375/containers/' + id + '/json');

        Request
            .header('Accept', 'application/json')
            .end(function (response) {
                console.log(response.body.NetworkSettings.Ports)
                res.send(response.body.NetworkSettings.Ports)


            })
    }
})

app.listen(port, () =&gt; {
    console.log(`app listening on port ${port}`)
})

</code></pre>
<p>Then simply query the webserver using curl inside of your container:</p>
<p><code>curl 172.1.0.1:3000/?id=yourcontainersname</code></p>
<p>The webserver will then respond with the ports exposed via docker for the name requested</p>
<p>The code may need tweaking of course for your needs but this worked out for me pretty well and I plan on expanding on this for myself a bit further.</p>
<p>For my purpose, I only need to grab one port number from the list of exposed ports so I can post configure some software automatically, here is it working :)</p>
<pre><code>[user@exampleserver]# curl localhost:3000?id=342128351638585344
32902
</code></pre>
<p>Side note, to get the single port, I did this:</p>
<pre class="lang-javascript prettyprint-override"><code>let responseKeys = Object.keys(response.body.NetworkSettings.Ports);
let selectedPort = responseKeys[3].replace(&quot;/tcp&quot;, &quot;&quot;);
console.log(selectedPort)

</code></pre>
<p>I hope this idea helps someone at least</p>

CC BY-SA 4.0
2022-01-28T04:37:10.703Z
2022-01-28T13:59:23.830Z
2022-01-28T13:59:23.830Z
TheProgrammingRaven
<p>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.</p>

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

CC BY-SA 4.0
2018-12-12T06:56:52.613Z
2018-12-12T06:56:52.613Z
Rajesh Rajendran
<p>Please refer the below link
You can use docker inspect for the same <a href="https://stackoverflow.com/questions/30342796/how-to-get-env-variable-when-doing-docker-inspect/30353018#30353018">docker inspect</a></p>

CC BY-SA 4.0
2018-12-12T06:48:38.080Z
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
CC BY-SA 4.0
2018-12-12T08:49:40.863Z
Oh yes, let me try if i can get some info
Sunil
CC BY-SA 4.0
2018-12-12T04:56:57.760Z
2018-12-12T04:56:57.760Z
Sunil
<p>I want to know which port(s) are exposed when user run the image.</p>

<pre><code>docker run -p 1000:1234 myimagename
</code></pre>

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

<p>Is there any env variable for this purpose?</p>

CC BY-SA 4.0
2019-01-11T07:16:43.247Z
May be this thread will help you? [Open Issue](https://github.com/moby/moby/issues/3778)
deosha
<docker><containers><dockerfile>
How to get exposed ports from inside of container?
agit
# How to get exposed ports from inside of container?

(Asked by: username_0 on 2018-12-11)

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?

**Tags:** docker, containers, dockerfile

> **Comments:**
> **username_1**: May be this thread will help you? [Open Issue](https://github.com/moby/moby/issues/3778)  

---

## 4 answers

### Answer by username_2 on 2019-06-10. Score: 1

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.

Instead you should 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 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.

If your application needs to be configured with the publicly reachable port (and probably IP or hostname), that should be injected as a configuration or environment variable. Trying to automate this from inside the container is error prone since your application may be exposed to users through a load balancer or NAT.


---

### Answer by username_3 on 2022-01-28. Score: 1

Tonight I decided to just query the docker api using a small express server running on the host node from within the container.
const express = require('express')
const app = express()
const port = 3000

var unirest = require('unirest');


app.get('/', (req, res) => {
    let id = req.query.id;

    if (!req.query.id) {
        res.send('I do not think you belong here.')
    } else {

        var Request = unirest.get('http://localhost:2375/containers/' + id + '/json');

        Request
            .header('Accept', 'application/json')
            .end(function (response) {
                console.log(response.body.NetworkSettings.Ports)
                res.send(response.body.NetworkSettings.Ports)


            })
    }
})

app.listen(port, () => {
    console.log(`app listening on port ${port}`)
})


Then simply query the webserver using curl inside of your container:
curl 172.1.0.1:3000/?id=yourcontainersname
The webserver will then respond with the ports exposed via docker for the name requested
The code may need tweaking of course for your needs but this worked out for me pretty well and I plan on expanding on this for myself a bit further.
For my purpose, I only need to grab one port number from the list of exposed ports so I can post configure some software automatically, here is it working :)
[user@exampleserver]# curl localhost:3000?id=342128351638585344
32902

Side note, to get the single port, I did this:
let responseKeys = Object.keys(response.body.NetworkSettings.Ports);
let selectedPort = responseKeys[3].replace("/tcp", "");
console.log(selectedPort)


I hope this idea helps someone at least


---

### Answer by username_4 on 2018-12-12. Score: 0

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.


---

### Answer by username_5 on 2018-12-12. Score: -1

Please refer the below link
You can use docker inspect for the same [docker inspect](https://stackoverflow.com/questions/30342796/how-to-get-env-variable-when-doing-docker-inspect/30353018#30353018)

> **Comments:**
> **username_0**: Hi @username_5,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.  
> **username_5**: Oh yes, let me try if i can get some info  

---

