添加虚拟网卡。这里不需要新建veth pair(ip link add vethfoo1 type veth peer name vethfoo2),而是直接将宿主机上附加的第二块虚拟网卡eth1改名为d-eth0,添加到前面的虚拟网络环境中(/var/run/netns/下的${NS_PID})。
1
ip linkset dev eth1 name eth1@eni netns ${NS_PID}
最后,启用虚拟网络环境中新添加的虚拟网卡,并重新设置好添加到容器前的IP和网关。
1 2 3 4 5 6
ip netns exec${NS_PID} ip linkset dev eth1@eni up ip netns exec${NS_PID} ip addr add ${CONTAINER_IP}/24 dev eth1@eni ip netns exec${NS_PID} route add -net 0.0.0.0/0 gw ${CONTAINER_GATEWAY}
ip netns exec ns1 ip link 1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
将网卡eth1添加到ns1中:
1
$iplinkset eth1 netns ns1
1 2 3 4 5
$ip netns exec ns1 ip link 1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 1000 link/ether 08:00:27:b3:6c:38 brd ff:ff:ff:ff:ff:ff
将网卡eth1重新添加到默认的ns中:
1
ip netns exec ns1 ip linkset eth1 netns 1
注意必须在ns1中设置,最后一个1表示,进程1所在的namespace。
删除netns:
1
ip netns delete ns1
[linux网络虚拟化][3]中给出了一个利用veth连接两个namespace的例子。
利用veth连接两个namespace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
ip netns add net0 ip netns add net1 ip link add type veth
ip linkset veth0 netns net0 ip linkset veth1 netns net1
ip netns exec net0 ip linkset veth0 up ip netns exec net0 ip address add 10.0.1.1/24 dev veth0
ip netns exec net1 ip linkset veth1 up ip netns exec net1 ip address add 10.0.1.2/24 dev veth1
ip netns exec net1 ping 10.0.1.1 PING 10.0.1.1 (10.0.1.1) 56(84) bytes of data. 64 bytes from 10.0.1.1: icmp_seq=1 ttl=64 time=0.036 ms 64 bytes from 10.0.1.1: icmp_seq=2 ttl=64 time=0.066 ms
两个namespace连接到bridge
创建三个ns,并利用veth连接:
1 2 3 4 5 6 7 8 9
ip netns add net0 ip netns add net1 ip netns add bridge ip link add type veth ip linkset dev veth0 name net0-bridge netns net0 //重新命名 ip linkset dev veth1 name bridge-net0 netns bridge ip link add type veth ip linkset dev veth0 name net1-bridge netns net1 ip linkset dev veth1 name bridge-net1 netns bridge
配置bridge,将另外两个ns的对端veth设备接入bridge:
1 2 3 4 5 6
ip netns exec bridge brctl addbr br ip netns exec bridge ip linkset dev br up ip netns exec bridge ip linkset dev bridge-net0 up ip netns exec bridge ip linkset dev bridge-net1 up ip netns exec bridge brctl addif br bridge-net0 ip netns exec bridge brctl addif br bridge-net1
配置两个ns中的veth设备:
1 2 3 4 5
ip netns exec net0 ip linkset dev net0-bridge up ip netns exec net0 ip address add 10.0.1.1/24 dev net0-bridge
ip netns exec net1 ip linkset dev net1-bridge up ip netns exec net1 ip address add 10.0.1.2/24 dev net1-bridge