Network namespaces provide isolation of the system resources associated with networking: network devices, IPv4 and IPv6 protocol stacks, IP routing tables, firewall rules, etc.
Docker uses network namespace to isolate container network from host network. There are other types of namespaces that support the implementation of container.
Create and view network namespace
ip netns add <namespace name>
ip netns [list]
Use network namespace
Running commands in given namespace needs to include netns exec.
ip netns exec <namespace name> ip link list
OR
ip -n <namespace name> ip link list
Communication between namespaces
The veth devices are virtual Ethernet devices. They can act as tunnels between network namespaces to create a bridge to a physical network device in another namespace, but can also be used as standalone network devices.
Create veth interface
Veth devices are always created in interconnected pairs. They are in default namespace.
ip link add <p1-name> type veth peer name <p2-name>
Attach veth pair to assigned namespace
Place one end of a veth pair in one network namespace and the other in another network, then communication between network namespaces is allowed.
ip link set <p1-name> netns <p1-ns>
ip link set <p2-name> netns <p2-ns>
OR do so while creating veth pair, 2 steps combined.
ip link add <p1-name> netns <p1-ns> type veth peer <p2-name> netns <p2-ns>
Assign IP address
ip -n <p1-ns> addr add <p1-ip> dev <p1-name>
ip -n <p2-ns> addr add <p2-ip> dev <p2-name>
A routing rule is automatically added when assigning the IP address.
Bring the interface up
ip -n <p1-ns> link set <p1-name> up
ip -n <p2-ns> link set <p2-name> up
Connectivity between host and namespaces
Create bridge interface
ip link add <interface name> type bridge
Bring the interface up
ip link set dev <interface name> up
Assign IP address
ip addr add <gateway ip> dev <interface name>