使用ip netns来操作network namespace
ip netns命令是用来操作network namespace的指令,具体使用方法如下。
创建一个network namespace:
#创建一个名为net-test的network namespace
[root@ganbing ~]# ip netns add net-test
列出系统中已存在的network namespace:
[root@ganbing ~]# ip netns ls
net-test
删除一个network namespace:
[root@ganbing ~]# ip netns delete net-test
在network namespace中执行一条命令:
命令格式
ip netns exec <network nameapce name> <command>
#比如显示net-test namespace的网卡信息,路由信息
[root@ganbing ~]# ip netns exec net-test ip addr
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
[root@ganbing ~]# ip netns exec net-test route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
其实,你如果觉得ip netns exec 来执行命令比较麻烦,还可以使用启动一个shell来配合:
#命令格式
ip netns exec <network nameapce name> bash
这样,就可以在上面执行命令,就好像使用者进入了这个network namespace中;如果要退出这个bash,则输入exit即可。
使用ip为network namespace配置网卡
当使用ip netns add命令创建了一个network namespace后,就拥有了一个独立的网络空间,可以根据需求来配置该网络空间,如添加网卡,配置IP,设置路由等。下面以之前建立的名为net-test的network namespace为例来演示如何进行这些操作。
当使用ip命令创建一个network namespace时,会默认创建一个回环设备(loopback interface:lo)。该设备默认不启动,最好将其启动。
[root@ganbing ~]# ip netns exec net-test ip link set dev lo up
在主机上创建两张虚拟网卡veth-1 和 veth-2:
[root@ganbing ~]# ip link add veth-1 type veth peer name veth-2
将veth-2设备添加到net-test这个network namespace中,veth-1留在宿主机中:
[root@ganbing ~]# ip link set veth-2 netns net-test
现在net-test这个network namespace就有两块网卡了(lo和veth-2),验证看一下:
[root@ganbing ~]# ip netns exec net-test ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
222: veth-2@if223: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 1000
link/ether 92:24:fd:44:c6:00 brd ff:ff:ff:ff:ff:ff link-netnsid 0
接下来可以为网卡分配IP并启动网卡:
#在主机上为veth-1配置IP并启动
[root@ganbing ~]# ip addr add 10.0.0.1/24 dev veth-1
[root@ganbing ~]# ip link set dev veth-1 up
#为net-test中的veth-2配置IP并启动
[root@ganbing ~]# ip netns exec net-test ip addr add 10.0.0.2/24 dev veth-2
[root@ganbing ~]# ip netns exec net-test ip link set dev veth-2 up
给两张网卡配置了IP后,会在各自的network namespace中生成一条路由,用ip route 或者 route -n查看:
#在主机中查看路由
[root@ganbing ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
...
10.0.0.0 0.0.0.0 255.255.255.0 U 0 0 0 veth-1
...
#在net-test中查看路由
[root@ganbing ~]# ip netns exec net-test route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
10.0.0.0 0.0.0.0 255.255.255.0 U 0 0 0 veth-2
上面这两条路由表明的意义是目的地址 10.0.0.0/24网络的IP包分别从veth-1和veth-2发出。
现在net-test这个network namespace有了自己的网卡、IP地址、路由表等信息,就相当于成了一台小型的“虚拟机”了。测试一下它的连通性,来检查配置是否正确。
原作者:thank037
原文链接:https://www.edgexfoundry.club/user/thank037/article/5bd666f073a5990001fb3b79