network namespace tips

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值