Jul 17, 2018

Publishing a specific docker port with -p

The -p flag can take a few different formats:

ip:hostPort:containerPort| ip::containerPort \
  | hostPort:containerPort | containerPort

You can omit either ip or hostPort, but you must always specify a containerPort to expose.

Docker will automatically provide an ip and hostPort if they are omitted.

All of these publishing rules will default to tcp. If you need udp, simply tack it on to the end such as -p 8888:8800/udp.

The ports need not match, but you must be careful to avoid port conflicts in the case of exposing ports on multiple containers.

The best way to avoid conflict is to let Docker assign the hostPort itself. In the same example as above, you could choose to run the container with docker run -p 3000 my_image instead of passing in a host port. In this case, Docker will select a port on your behalf.

You can specify as many port mappings with -p as you fancy.

You can see what port was selected by running the command docker port $container_id | $container_name.