network namespace tips

linux network namespace offer an intra net in our network. A network namespace includes ethernet interfaces and ip routes.

linux network namespace offer mechanism to separate different networks , which is  requirement for container virtualization .

here some tips to create a network namespace and connect it to the Internet.

1. create network namespace

$ sudo ip netns add <name>

eg sudo ip netns add blue

2. list net namespace

$ sudo ip netns list

3. create virtual ethernet tube

ip link add veth0 type veth peer name veth1

after this command, there will be two more net interfaces, you can check with ip link list


4. add interface to net namespace

sudo ip link set veth1 netns blue

5. check net namespace link

ip netns exec blue ip link list

check a net namespace's link

6. configure interfaces in the net namespace

ip netns exec blue ifconfig veth1 10.1.1.1/24 up

7. ifconfigre veth0 on the host

ifconfig veth0 10.1.1.2/24 up

8. add default route for net namespace

ip netns exec blue route add default gw 10.1.1.2

check route table with:

bash-4.3> sudo ip netns exec blue route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.1.1.2        0.0.0.0         UG    0      0        0 veth1
10.1.1.0        0.0.0.0         255.255.255.0   U     0      0        0 veth1

9. ping veth0

ip netns exec blue ping 10.1.1.2

PING 10.1.1.2 (10.1.1.2) 56(84) bytes of data.
64 bytes from 10.1.1.2: icmp_seq=1 ttl=64 time=0.084 ms
64 bytes from 10.1.1.2: icmp_seq=2 ttl=64 time=0.072 ms
64 bytes from 10.1.1.2: icmp_seq=3 ttl=64 time=0.076 ms

10. enable nat to foward packet from this net namespace

echo 1 > /proc/sys/net/ipv4/ip_forward

 sudo iptables -A POSTROUTING -t nat -j MASQUERADE -s 10.1.1.0/24

11. now ping extern network

bash-4.3> sudo ip netns exec blue ping 111.161.68.235
PING 111.161.68.235 (111.161.68.235) 56(84) bytes of data.
64 bytes from 111.161.68.235: icmp_seq=1 ttl=46 time=111 ms
64 bytes from 111.161.68.235: icmp_seq=2 ttl=46 time=111 ms
^C
--- 111.161.68.235 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 111.178/111.215/111.253/0.335 ms

reference:

http://blog.scottlowe.org/2013/09/04/introducing-linux-network-namespaces/

發佈了55 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章