host-gateway試驗拓撲
本文介紹flannel一種沒有封解包的容器跨主機通信方案:flannel host-gateway模式,相比于UDP和vxlan模式,host-gateway模式沒有額外的封解包過程,單純依靠路由表項配置實現容器跨主機通信網絡。其模型如下圖:
需要說明的是:
l 兩臺機器均已打開內核ipv4轉發開關
l 容器分配的IP網段為1.1.0.0/16
l node1維護1.1.1.0/24 IP段
l node2維護1.1.2.0/24 IP段
l 兩臺主機二層互通
具體的實驗拓撲如下所示:
node1操作
ip netns add netns1
ip link add veth1 type veth peer name veth2
ip link set veth2 netns netns1
ip netns exec netns1 ifconfig veth2 1.1.1.2/24 up
ip link add name cni0 type bridge
ifconfig cni0 1.1.1.1/24 up
ip link set dev veth1 master cni0
ifconfig veth1 up
ip netns exec netns1 ip route add default via 1.1.1.1 dev veth2
ip netns exec netns1 route -n
node2操作
ip netns add netns2
ip link add veth3 type veth peer name veth4
ip link set veth4 netns netns2
ip netns exec netns2 ifconfig veth4 1.1.2.2/24 up
ip link add name cni0 type bridge
ifconfig cni0 1.1.2.1/24 up
ip link set dev veth3 master cni0
ifconfig veth3 up
ip netns exec netns2 ip route add default 1.1.2.1 dev veth4
ip netns exec netns2 route -n
分析路由
// node1 查看路由
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.12.1 0.0.0.0 UG 0 0 0 eth0
1.1.1.0 0.0.0.0 255.255.255.0 U 0 0 0 cni0
10.0.12.0 0.0.0.0 255.255.252.0 U 0 0 0 eth0
// node2 查看路由
#route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.12.1 0.0.0.0 UG 0 0 0 eth0
1.1.2.0 0.0.0.0 255.255.255.0 U 0 0 0 cni0
10.0.12.0 0.0.0.0 255.255.252.0 U 0 0 0 eth0
根據路由規則,此時node1上可以ping通自己的1.1.1.2,node2上可以ping通自己的1.1.2.2,但是node1上ping不通node2上的1.1.2.2,node2上也ping不通node1上1.1.1.2。
說明:
// node1
ping -c 1 1.1.1.2 可以通
ping -c 1 1.1.2.2 不通
// node2
ping -c 1 1.1.2.2 可以通
ping -c 1 1.1.1.2 不通
添加路由
因為node1和node2二層互通,要使能在node1上訪問node2上的1.1.2.2(veth4),可以考慮在node1上添加一條網關是node2 eth0 IP的路由;考慮回程報文,node2也應該加一條網關是node1 eth0 IP的路由,于是有:
// node1 操作
ip route add 1.1.2.0/24 via 10.0.12.7 dev eth0
route -n
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.12.1 0.0.0.0 UG 0 0 0 eth0
1.1.1.0 0.0.0.0 255.255.255.0 U 0 0 0 cni0
1.1.2.0 10.0.12.7 255.255.255.0 UG 0 0 0 eth0
10.0.12.0 0.0.0.0 255.255.252.0 U 0 0 0 eth0
// node2 操作
ip route add 1.1.1.0/24 via 10.0.12.11 dev eth0
route -n
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.12.1 0.0.0.0 UG 0 0 0 eth0
1.1.1.0 10.0.12.11 255.255.255.0 UG 0 0 0 eth0
1.1.2.0 0.0.0.0 255.255.255.0 U 0 0 0 cni0
10.0.12.0 0.0.0.0 255.255.252.0 U 0 0 0 eth0
再次驗證
在node1上ping node2上的1.1.2.2以及在node2上ping node1上的1.1.1.2:
以下實驗均通過ping測試
ping -c 1 1.1.2.2
ip netns exec netns1 ping -c 1 1.1.2.2
ping -c 1 1.1.1.2
ip netns exec netns2 ping -c 1 1.1.1.2
實驗小結
flannel host-gateway模式正如host-gateway的含義,通過一條目標主機(host)IP作為網關(gateway)的路由實現容器跨主機通信。相比于UDP模式和vxlan模式,少了tun設備和vxlan設備的封解包過程,在性能上有更大的優勢。但是直連路由要求主機間二層互通,這在一定程度上限制了host-gateway的使用場景,特別是公有云環境,不太好滿足所有節點二層互通的條件。上文的路由是手動配置的,在flannel的實現中,是通過flanneld進程完成該操作的:每個節點上起一個flanneld進程,flanneld進程起來后注冊本節點管理的網段和宿主機IP等信息到etcd(直連etcd或者通過apiServer接口),并且監聽其它節點的注冊信息,當發現有新節點加入集群時,便會在本節點增加一條網關是新節點IP的路由。