Daniel Sorichetti
Daniel Sorichetti

Reputation: 1951

Letting a container know its exposed ports in Docker

Let's say I start a container, exposing a random port to 80 like this: docker run -d -p 80 -name my_container username/container.

Is there any way to tell my_container on which host's port his 80 was exposed?

Edit: My situation:

I'm running Apache to serve some static HTML files, and an Go API server on this container. I'm exposing both services here. The static files request data from the server via javascript on the user's browser, but to be able to do this, the clients need to know on which port the API server is made available, to be able to connect to it. Is this the appropriate way to do this?

Upvotes: 1

Views: 280

Answers (2)

icecrime
icecrime

Reputation: 76755

I don't think there exists an easy to tell from the container the host port on which its port 80 was exposed, but I also believe there is a good reason for that: making the container dependent on this would make it dependent on its containing environment, which goes against Docker's logic.

If you really need this, you could pass the host port as an environment variable to the container using the -e flag (assuming that the host port is fixed), or rely on a hack such as mounting the Docker socket in the container (-v /var/run/docker.sock:/var/run/docker.sock) and have it "inspect himself" (which is similar to what progrium/ambassadord does to implement its omni mode).

Maybe you should clarify why you need this information in the first place and perhaps there's a simpler solution that can help you achieve that.

Upvotes: 1

Marcus Hughes
Marcus Hughes

Reputation: 5503

You can run docker ps which will show the ports, for example

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                   NAMES
containerid         ubuntu:14.04        /bin/bash           14 seconds ago      Up 13 seconds       0.0.0.0:49153->80/tcp   my_container

In this instance it is 49153.

Also docker inspect will tell you lots about your container, including the port mappings

$ docker inspect my_container | grep HostPort
"HostPort": "49153"

Upvotes: 0

Related Questions