在虚拟化环境中,默认net namespace怎么和新创建的net namespace通信呢?答案是使用veth pair。
创建一对veth接口,这两个接口相当于点对点的两端。
ip link add veth0 type veth peer name veth1
然后添加ip地址和路由条目即可:
$ ip netns add net0 || exit 0
$ ip link add veth0 type veth peer name veth1
$ ip link set veth0 up
$ ip -4 addr add 10.0.0.1/32 dev veth0
$ ip -4 route add 10.0.0.2/32 dev veth0
$ ip link set veth1 netns net0
$ ip netns exec net0 ip link set veth1 up
$ ip netns exec net0 ip -4 addr add 10.0.0.2/32 dev veth1
$ ip netns exec net0 ip -4 route add 10.0.0.1/32 dev veth1
在net0 namespace中
/ # ifconfig
veth1 Link encap:Ethernet HWaddr 46:86:5F:40:E1:41
inet addr:10.0.0.2 Bcast:0.0.0.0 Mask:255.255.255.255
inet6 addr: fe80::4486:5fff:fe40:e141/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:26 errors:0 dropped:0 overruns:0 frame:0
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4574 (4.4 KiB) TX bytes:516 (516.0 B)
/ # ip route
10.0.0.1 dev veth1 scope link
在主机的默认 namespace中
$ ifconfig veth0
veth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.0.1 netmask 255.255.255.255 broadcast 0.0.0.0
inet6 fe80::acc8:3fff:feec:6dd5 prefixlen 64 scopeid 0x20<link>
ether ae:c8:3f:ec:6d:d5 txqueuelen 1000 (Ethernet)
RX packets 9 bytes 726 (726.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 48 bytes 8342 (8.3 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
$ ip route
default via 192.168.137.1 dev eth0 proto static metric 100
10.0.0.2 dev veth0 scope link
169.254.0.0/16 dev eth0 scope link metric 1000
172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 linkdown
192.168.137.0/24 dev eth0 proto kernel scope link src 192.168.137.100 metric 100
在主机中ping
$ ping 10.0.0.2
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.077 ms
64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.029 ms
^C
--- 10.0.0.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1003ms
rtt min/avg/max/mdev = 0.029/0.053/0.077/0.024 ms
参考:
https://serverfault.com/questions/895658/inter-namespace-communication-over-linux-bridge