Service Cluster IP 是一个虚拟 IP,是由 Kubernetes 节点上的 iptables 规则管理的。
[root@localhost ~]# kubectl get service
NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes 10.254.0.1 <none> 443/TCP 29d
service 10.254.92.25 <none> 8888/TCP 18m
可以通过 iptables-save
命令打印出当前节点的 iptables 规则,因为输出较多,这里只截取与 httpd-svc
Cluster IP 10.254.92.25
相关的信息:
[root@localhost ~]# iptables-save > /etc/sysconfig/iptables
[root@localhost ~]# vim /etc/sysconfig/iptables
*nat
-A KUBE-SERVICES -d 10.254.92.25/32 -p tcp -m comment --comment "default/service:tcp-8888-80-dz3ws cluster IP" -m tcp --dport 8888 -j KUBE-SVC-NLT2S6Z5R6SPM3WC
这两条规则的含义是:
- 其他源地址访问
httpd-svc
,跳转到规则KUBE-SVC-NLT2S6Z5R6SPM3WC
KUBE-SVC-NLT2S6Z5R6SPM3WC
规则如下:
[root@localhost ~]# cat /etc/sysconfig/iptables | grep -i KUBE-SVC-NLT2S6Z5R6SPM3WC
:KUBE-SVC-NLT2S6Z5R6SPM3WC - [0:0]
-A KUBE-SVC-NLT2S6Z5R6SPM3WC -m comment --comment "default/service:tcp-8888-80-dz3ws" -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-YK7OVCO7FZOY7VZM
-A KUBE-SVC-NLT2S6Z5R6SPM3WC -m comment --comment "default/service:tcp-8888-80-dz3ws" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-HRGN3N24VWJ3ZK4U
-A KUBE-SVC-NLT2S6Z5R6SPM3WC -m comment --comment "default/service:tcp-8888-80-dz3ws" -j KUBE-SEP-VWXBMMSYUGMCZBTJ
- 1/3 的概率跳转到规则 KUBE-SEP-YK7OVCO7FZOY7VZM
- 1/3 的概率(剩下 2/3 的一半)跳转到规则
KUBE-SEP-HRGN3N24VWJ3ZK4U
- 1/3 的概率跳转到规则
KUBE-SEP-VWXBMMSYUGMCZBTJ
上面三个跳转的规则如下:
-A KUBE-SEP-YK7OVCO7FZOY7VZM -s 172.17.56.2/32 -m comment --comment "default/service:tcp-8888-80-dz3ws" -j KUBE-MARK-MASQ
-A KUBE-SEP-YK7OVCO7FZOY7VZM -p tcp -m comment --comment "default/service:tcp-8888-80-dz3ws" -m tcp -j DNAT --to-destination 172.17.56.2:80
-A KUBE-SEP-HRGN3N24VWJ3ZK4U -s 172.17.56.4/32 -m comment --comment "default/service:tcp-8888-80-dz3ws" -j KUBE-MARK-MASQ
-A KUBE-SEP-HRGN3N24VWJ3ZK4U -p tcp -m comment --comment "default/service:tcp-8888-80-dz3ws" -m tcp -j DNAT --to-destination 172.17.56.4:80
-A KUBE-SEP-VWXBMMSYUGMCZBTJ -s 172.17.56.5/32 -m comment --comment "default/service:tcp-8888-80-dz3ws" -j KUBE-MARK-MASQ
-A KUBE-SEP-VWXBMMSYUGMCZBTJ -p tcp -m comment --comment "default/service:tcp-8888-80-dz3ws" -m tcp -j DNAT --to-destination 172.17.56.5:80
即将请求分别转发到后端的三个 Pod。通过上面的分析,我们得到如下结论:
iptables 将访问 Service 的流量转发到后端 Pod,而且使用类似轮询的负载均衡策略。
另外需要补充一点:Cluster 的每一个节点都配置了相同的 iptables 规则,这样就确保了整个 Cluster 都能够通过 Service 的 Cluster IP 访问 Service。