Why and how to use port mapping in Docker? An introduction for beginners.
In my experience working with software engineers, I have noticed time and again that the concept of of port mapping with Docker containers is one of the more challenging concepts. The typical problems include:
- Why we need ports in the first place?
- How to configure port numbers for containers?
In this article I will focus on these but also touch briefly on adjacent topics. The incremental approach I will use works quite well in practice and I hope it will work for you, too.
Why do we need Ports?
Assume you have a computer running. This can be physical or virtual. For our exploration it does not matter. That computer (or virtual machine) is connected to an IP network. To uniquely identify the computer on that IP network it has an IP address. This is a number combination such as 172.19.16.1. This is an example. You can find out the IP address of your computer by typing in a terminal
This may result in an output similar to the following:
Here the IP address for my computer is listed as 172.19.16.1. Yours may be different. When a different computer on the same IP network wants to talk to your computer it can use that IP address to send packages. The computer receives the packages, processes them, and sends a reply, i.e., packages, to the other computer.
I will leave out the fact that we ran out of IP addresses long time ago, techniques to overcome that problem and concepts such as different versions of IP addresses, routing, subnets, network address translation, public/private IP addresses and many more. We do not need to understand these for our discussion.
Now that we understand how a different computer can talk to your computer using your computer’s IP address, let us assume that we run more than one program or process on your computer. For example, you may have a web server running on your computer. You may also be sharing files on your computer. Both are made possible by running different processes on your computer.
If a different computer sends packages, i.e., requests, to your computer, it needs to know which process is handling the incoming packages. How does the host, i.e., your computer know whether to send a request to Process A or to Process B?