2

I haven't fully understood the way port forwarding works with docker.

My scenario looks like this:

  • I have a Dockerfile that exposes a port (in my case it's 8000)
  • I have built an image using this Dockerfile (by using "docker build -t test_docker")
  • Now I created several containers by using "docker run -p 808X:8000 -d test_docker"
  • The host reacts on calling its IP with the different ports I have assigned on "docker run"

What exactly does this EXPOSE command do in the Dockerfile? I understood that the docker daemon itself handles the network connections and while calling "docker run" I also tell what image should be used...

Thanks

AntonSack
  • 1,021
  • 2
  • 25
  • 47
  • Possible duplicate of [What is the difference between "expose" and "publish" in Docker?](https://stackoverflow.com/questions/22111060/what-is-the-difference-between-expose-and-publish-in-docker) – David Maze Jul 24 '18 at 23:50

2 Answers2

0

OK, I think I understood the reason.

If you are listening on ports within your application, you need to expose exactly this port. E.g.

 HttpServer.bind('127.0.0.1', 8000).then((server) {...}

will need "EXPOSE 8000". Like this you can listen to several to several ports in your app but then need to expose them all.

Am I right?

AntonSack
  • 1,021
  • 2
  • 25
  • 47
  • If you bind to 127.0.0.1, your process won't be accessible outside the container. It must bind to 0.0.0.0 (even if a later `docker run -p` option remaps it to a different port or limits it to a specific host interface). – David Maze Jul 24 '18 at 23:49
0

Exposing ports in your dockerfile allows you to spin up a container using the -P(See here) flag on the docker run command.

A simple use case might be that you have nginx sitting on port 80 on a load balancing server, and it's going to load balance that traffic across a few docker conatiners sitting on a coreos docker server. Since each of your apps use the same port, 8000, you wouldn't be able to get to them individually. So docker would map each container to a high random, and non conflicting port on the host. So when you hit 49805, it goes to container 1s 8000, and when you hit 49807, it goes to container 2s 8000.

Harry Moreno
  • 10,231
  • 7
  • 64
  • 116
Sean Murphy
  • 829
  • 6
  • 5