Publish a Port On Docker Containers

Today, I’d like to share a useful Docker tip with you. You may have noticed that Docker containers are granted access to the outside world only through the Docker host machine’s network stack.

In other words, any service listening on a TCP or UDP port can be accessed from your Docker host machine’s shell or from an external Docker client as long as that Docker host machine’s IP address is in the container’s /etc/hosts file.

The Docker daemon itself does not listen on any TCP/UDP ports to keep Docker containers secure. If your Docker host machine has multiple network interfaces, Docker containers may be able to communicate with external hosts through those other network interfaces when you use Docker port forwarding. Docker containers can also access the Docker host’s network stack directly through Docker links, but it’s important to remember that Docker links are local to a single Docker container and will not allow you to publish ports from one Docker container to another Docker container on the same Docker host machine.

In this article, I will demonstrate how to publish a port on Docker containers. To do this, we will need to attach a Docker container’s Docker host machine’s network stack directly by using Docker’s –network parameter with the docker run command and then configure our Docker container to use that network stack with the -p flag so that Docker will create and publish both the TCP and UDP ports when we start up our Docker container.

Publish a Port

To open a port on a Docker container we use the -p switch. The below example will open create a port forwarding from the Docker host port 8080 to the container’s port 80.

docker run -it --rm -p 8080:80 ubuntu:14.04 bash

Posted

in

by