session

~/chopper

article

How Containers Reach the internet

Diagram: container and host namespaces, veth pair, docker0 bridge, routing, NAT masquerade, host eth0 to internet

Linux Networking

Computers need Network interface cards (NIC) which can be physical or virtual to reach the internet. Every process belongs to a network namespace. Kernel’s networking stack can create and manage network interfaces. A network namespace has its own set of network interfaces for isolation.

How Network Interfaces are created

When system boots, it detects the network interface card hardware and loads the appropriate driver which registers the network devices with the kernel. That creates network interfaces like eth0. Virtual Network Interfaces like Lo (used for localhost like 127.0.0.1) is created automatically while other network interfaces like veth pairs and bridge are created dynamically through system calls (netlink).

Each network interface has its own IP address and MAC address while namespace has its set of network interfaces, firewall rules, NAT and routing table. Namespaces are isolated with each other so that processes with different namespaces can use the same port without conflicting. Namespaces can be connected with veth pairs, point to point cable like one end connected with one namespace and one end connected with another namespace. Also, network interfaces can be connected by a bridge which acts as virtual switch to which network interfaces within the namespace connect.

Containers run inside their own network namespaces. Each namespace has its own eth0 interface. Container namespace itself can not access to the internet without linking to host namespace as eth0 interfaces in container and host namespaces are different and only host network interface like (eth0) can directly communicate with the internet.

Container namespace and host namespace are isolated with each other, they are connected with veth pair interface, one end resides at the container hostname and one end at the host hostname.

When a container sends a traffic, it flows through the container’s eth0 interface, across veth pairs into the host namespace, then through the bridge. Host uses routing tables to forward the traffic,finally to the internet through eth0 interface.

Before packets leave the host, host applies Network Address Translation (NAT) to resolve the private ip address of container to the host’s ip address to allow the traffic to be routed on the internet.

Thanks for reading.