Linux Network Namespace

Posted by Henry Du on Monday, September 7, 2020

Linux Network Namespace

This is study notes from Network Namespace

Introduction

Network namespace is using for container like docker to implement network isolation. When we create a container, we create a network namespace for it. So the container is not able to see host network such as routing table and arp table. The container has its own routing table and arp table in its namespace.

Operation Commands

To create a new network namespace, say red, using a command:

ip netns add red

List command

ip netns

If we want to take a look new created network namespace network link, using the command

ip netns exec red ip link

OR

ip -n red link

The same command pattern applies to arp table

ip netns exec red arp

And routing table

ip netns exec red route -n

We can create a virtual cable between container network to host network. When docker daemon start, there is a docker0 interface. It is a linux kernel maintained L2 virtual switch.

# Attached interface to namespace
ip link set veth-red netns red

# assign IP address
ip -n red address add 192.168.15.1 dev veth-red

# bring up the interface
ip -n red link set veth-red up

If we have multiple containers want to connect to each other, then we need a virtual switch. Docker created a docker0 as a linux bridge. We can create our own

ip link add v-net-0 type bridge
ip link set dev v-net-0 up

Then, we want to create a virtual cable between container and virtual switch

ip link add veth-red type veth peer name veth-red-br
# 
ip link set veth-red-br master v-net-0

Assign a IP to the bridge interface (or VLAN interface), then the host can communicate with container network.

ip adds add 192.168.15.5/24 dev v-net-0

NAT and DNAT by iptables

How the red container can reach outside host, we need to add NAT into iptables.

# add gateway to the container routing table
ip netns exec red ip route add 192.168.1.0/24 via 192.168.15.5
# add NAT into iptables
iptables -t nat -A POSTROUTING -s 192.168.15.0/24 -j MASQUERADE

If we want to outside world to access the internal container, we need to add port forwarding role to the iptbales.

iptables -t nat -A PREROUTING —sport 80 —to-destination 192.168.15.2:80 -j DNAT