What is the principle of port mapping in Docker?
“Port mapping in Docker is the process of mapping ports from within a Docker container to ports on the host machine, allowing access to services within the container through the host’s IP address and port.”
Docker utilizes Linux’s network namespaces to achieve port mapping. In Linux, each container has its own network namespace with a separate IP address and port space. When a container is launched, Docker creates a virtual network interface for the container, which is bound to the container’s network namespace.
In port mapping, Docker binds the ports inside the container to the ports on the host. When a service inside the container listens on a certain port, Docker will forward a specific port on the host to the corresponding port inside the container. This way, when the host receives a request from the outside, it will forward the request to the service inside the container.
Specifically, Docker uses the iptables tool to implement port mapping. When a container starts, Docker creates an iptables rule on the host that forwards a specific port on the host to the corresponding port inside the container. This allows all requests sent to the specified port on the host to be forwarded to the container internally.
In summary, Docker’s port mapping works by creating iptables rules that bind the host’s ports with the container’s ports, allowing access to external services.