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/

本文介绍如何使用Linux网络命名空间创建内部网络,并将其连接到互联网。通过创建命名空间、虚拟以太网管道及配置路由等步骤,实现容器化的网络隔离。
2742

被折叠的 条评论
为什么被折叠?



