場景
在Kubernetes中引入外部服務(wù),大致分為兩種場景:
- 容器訪問外部獨(dú)立服務(wù)
部署在Kubernetes集群中的容器需要訪問外部服務(wù)時(shí),例如MySQL時(shí),需要在代碼中填寫MySQl的外部IP地址。引入Endpoint后,只需要?jiǎng)?chuàng)建外部服務(wù)的Endpoint和Service后,容器就能通過ServiceName訪問外部服務(wù)了。
- LoadBalance引入外部服務(wù)
Kubernetes開發(fā)的負(fù)載均衡器,都有一個(gè)優(yōu)點(diǎn),能夠?qū)崟r(shí)更新后端容器服務(wù)的IP地址。基于這點(diǎn),現(xiàn)公司架構(gòu),可以利用K8s負(fù)載均衡器的特性,將自己傳統(tǒng)的負(fù)載均衡器納入到K8s的管理中來。
方案
1. 容器訪問外部獨(dú)立服務(wù)
- 外部服務(wù)的Service,以Mysql為例
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
- 外部服務(wù)的Eedpoint
apiVersion: v1
kind: Endpoints
metadata:
name: mysql-production
namespace: default
subsets:
- addresses:
- ip: 10.17.72.2
nodeName: 10.17.72.2
ports:
- port: 3306
2. LoadBalance引入外部服務(wù)
- 外部服務(wù)的Service,以Nginx為例
apiVersion: v1
kind: Service
metadata:
labels:
k8s-app: nginx
name: nginx
spec:
clusterIP: 10.33.80.219
ports:
- name: port443
port: 443
protocol: TCP
targetPort: 443
- name: port80
port: 80
protocol: TCP
targetPort: 80
sessionAffinity: ClientIP
type: ClusterIP
- 外部服務(wù)的Endpoint
apiVersion: v1
kind: Endpoints
metadata:
name: nginx
subsets:
- addresses:
- ip: 10.20.6.129
nodeName: 10.17.64.38
- ip: 10.20.6.194
nodeName: 10.17.64.39
- ip: 10.20.7.1
nodeName: 10.17.64.40
ports:
- port: 443
name: port443
protocol: TCP
- port: 80
name: port80
protocol: TCP
在LoadBalance上可以看到Service的更新
# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 10.33.80.219:80 rr persistent 10800
-> 10.20.6.129:80 Masq 1 0 0
-> 10.20.6.194:80 Masq 1 0 0
-> 10.20.7.1:80 Masq 1 0 0
TCP 10.33.80.219:443 rr persistent 10800
-> 10.20.6.129:443 Masq 1 0 0
-> 10.20.6.194:443 Masq 1 0 0
-> 10.20.7.1:443 Masq 1 0 0