Docker networking by namespaces
2 min readOct 10, 2021
Here we talk about how docker achieves it’s networking through namespaces
- Create Namespace
sudo ip netns add <namespace name>
Eg: sudo ip netns add red
- View namespaces
sudo ip netns
- Execute commands in namespace from host
sudo ip netns exec <namespace name> ip link
Eg: sudo ip netns exec red ip link
Eg: sudo ip netns exec red arpAlsosudo ip -n red link
- Create a linux bridge in host
sudo ip link add v-net-0 type bridge
sudo ip link set dev v-net-0 up
- Create a veth pair in host
sudo ip link add veth-red type veth peer name veth-red-br
- Link one end of the veth pair (veth-red) to namespace (red)
sudo ip link set veth-red netns red
- Link other end of the veth pair (veth-red-br) to linux bridge (v-net-0)
sudo ip link set veth-red-br master v-net-0
- Assign IP address to namespace (red) veth (veth-red) interface
sudo ip -n red addr add 192.168.15.1 dev veth-red
sudo ip -n red link set veth-red up
- Assign IP address to linux bridge (v-net-0)
sudo ip addr add 192.168.15.5/24 dev v-net-0
- Ping the namespace (red)
ping 192.168.15.1
- Ping from namespace (red) to host
sudo ip netns exec red ping 192.168.15.5
- Enable access for namespace (red) to other interfaces in the host (add route and NAT)
sudo ip netns exec red ip route add 192.168.1.0/24 via 192.168.15.5
sudo iptables -t nat -A POSTROUTING -s 192.168.15.0/24 -j MASQUERADE
- Enable internet access to the namespace (Add default route and enable IP forwarding)
sudo ip netns exec red ip route add default via 192.168.15.5
sudo ip netns exec red ping 8.8.8.8
Reference: https://www.youtube.com/watch?v=j_UUnlVC2Ss