Yes, a -p
works so well, because it’s opening a localport that is actually a redirect to an address that is NATed behind the docker bridged networking.
It is not docker running on the Linux machine that is instigating this port opening. The invoking agent on the Mac knows exactly which port needs to be redirected and how.
How could this work with --net=host? Docker in this case even the docker daemon running on the virtualized Linux machine doesn’t even actually know which port the container opened, because the container has done an “end run” around docker straight to the namespaced kernel.
So, now, considering that the docker daemon doesn’t even know what port was eventually opened by the container, how would you expect the OSX invoker to even know?
Is the behavior inconsistent? Yes, it is. Is there really anything they can do without essentially setting up a bridged NAT in the first place, and just replicating -p
? No, there really isn’t.
Docker was designed with the intent that -p
is the way things will work. (Otherwise, it can’t track the opened ports.)
You might find it frustrating, but it is not a show-stopper, it is in fact, something that they cannot make work without instrumenting up the open TCP socket syscall in the Linux virtual guest, AND setting up a bridged network in the first place, and even then, ok, the container opens port 0, which is “random unprivileged port”, the Linux machine opens up port 64435 on it’s virtual linux host, but a different process running on the machine’s OSX host already has port 64435 (like, say a web-browser) open. Now, the Linux machine is stuck telling the host “hey, open up port 64435 and redirect it to me” and the host saying “no can do, it’s already open for a different program”.
What then? Crash your container or return a “port already open” syscall error? Now the behavior is still different from Linux, because sometimes the OSX-housed container will barf at start up claiming “port already open” when you’re opening port 0, which is supposed to assign an unused port before opening it, and thus should never barf up “port already open” unless the machine has already exhausted all available ports.
This is a complex problem, and many of the steps in the way are better solved with using pre-allocated ports on the invoking docker command-line with -p
which is kind of why they designed its common-use-case to use that method in the first place.