Senior
What happens when port forwarding in Docker? How is it implemented?
sobes.tech AI
Answer from AI
When port forwarding in Docker occurs, it maps the container's port to the host's port so that the service inside the container is accessible from outside.
Implementation:
- In Docker, when starting a container with the
-p <host_port>:<container_port>flag, a rule is created in the host's network stack. - This rule redirects incoming TCP/UDP connections to the specified host port into the container on the corresponding port.
- Docker uses mechanisms like iptables (on Linux) or other networking technologies to set up NAT and port forwarding.
For example, the command:
docker run -p 8080:80 nginx
means that all requests to port 8080 on the host will be forwarded to port 80 inside the container running nginx.
Thus, port forwarding allows containers to be accessible from outside despite network isolation.