'Where does my docker container get internet from and how does it work

I have just created and ran a docker container with a centos image . I was suprised to notice I can ping 1.0 or 1.1.1.1 as well as if I added a name server I can ping google etc. I can even ping my router private IP.

How does this work since my container private IP is something like 172.x.x.x while my network address in my house is 192.x.x.x. ?



Solution 1:[1]

By default each container is started in its own network namespace and connected to a bridge device using a virtual network interface.

Within its own network namespace the container also has its own routing table: if you're container e.g. has IP address 172.12.0.2/16 it usually then has 172.12.0.1 as its default gateway and that IP is assigned to the bridge device on the host, i.e., the host is part of multiple networks (virtual networks setup by docker and your physical home network) and acts as a router for the containers.

For this to work properly IP forwarding needs to be enabled, firewall/iptables rules to be setup correctly and in most cases the private IP addresses of the containers need to be masqueraded. docker already takes care of all of this for you in its default configuration.

For more see the docker networking documentation and especially the bridge documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 acran