Exploring Docker Networking – Ports and Forwarding


So upsides and downsides with the lowercase/uppercase flags here.

  • With the uppercase P, Docker handles everything for you so you don’t have to worry about port conflicts.  You can repeat the docker run command over and over and never have a problem.  On the other hand, it registers all available ports on all available addresses.  And the assignment is effectively random.
  • With the lowercase p, you must manually assign ports which means you have to be cognizant of how things are mapped.  No mapping a container to port 80 more than once.  But you also have more control over the mappings as well.

Host and MACVLAN

Quickly I wanted to answer, in case you are using host or MACVLAN networking, why the -P and -p flags are ignored.  That’s right, they don’t do anything at all.

In the case of host networking, the containers and hosts share the same network stack.  There is no need for port forwarding because my container is essentially directly available at my server’s IP address.  This means that whenever I spin up an nginx container in host mode, port 80 is immediately available on the server’s IP address at port 80.  This also means that you can’t run more than one nginx container on a server, at least out of the box, at the same time – sadface.  If you run an additional one, it shuts down the previous one.  Seriously though, this is a limitation with host networking that I addressed in the previous blog post which hopefully makes more sense now.

For MACVLAN the flags are also ignored but for a different reason.  That is because the container IPs are actually available outside the host.  So if I were using MACVLAN networking, I would be allocating “real” networks and “real” IPs to the containers.  So my container that is on would be pingable and accessible from my laptop without any extra work.  If it helps, you can think of this like VMs running on an ESXi host (even though these are NOT VMs).  You wouldn’t need port forwarding on the ESXi host because the VM IPs are generally available on the larger network.  There is the standard limitation of not exposing the same port twice per container, but as we said this is nothing new.  Again there is no reason to do port forwarding in this case.

Once again hope this was helpful and look forward to writing up the next one!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s