可以使用 Linux 提供的 veth pair 來完成通訊。下面顯示兩個 namespace 之间的网络拓扑图:
3.1 ip link add type veth 建立 veth pair
1 2 3 4 5 6 7 8 9 10 11 12
# 查看veth
$ ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000 link/ether 00:50:56:a9:e9:17 brd ff:ff:ff:ff:ff:ff 3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default link/ether 02:42:8b:f3:61:ac brd ff:ff:ff:ff:ff:ff
$ ip link 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000 link/ether 00:50:56:a9:e9:17 brd ff:ff:ff:ff:ff:ff 3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default link/ether 02:42:8b:f3:61:ac brd ff:ff:ff:ff:ff:ff 8: veth2@if9: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000 link/ether 6e:86:2f:10:5c:50 brd ff:ff:ff:ff:ff:ff link-netnsid 0 $ ip link set veth2 netns net2
$ ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000 link/ether 00:50:56:a9:e9:17 brd ff:ff:ff:ff:ff:ff 3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN mode DEFAULT group default link/ether 02:42:8b:f3:61:ac brd ff:ff:ff:ff:ff:ff
3.3 給 veth pair 配上 ip 地址
1 2 3 4 5 6 7 8 9 10 11 12 13
# 给net0 namespace 空间 veth0 up $ ip netns exec net1 ip link set veth1 up
$ ip addr add 10.1.1.1/24 dev veth1 # veth0 up 设置ip 启动起来
$ ip route 10.1.1.0/24 dev veth1 proto kernel scope link src 10.1.1.1