場景
在Kubernetes中引入外部服務,大致分為兩種場景:
- 容器訪問外部獨立服務
部署在Kubernetes集群中的容器需要訪問外部服務時,例如MySQL時舱污,需要在代碼中填寫MySQl的外部IP地址胰默。引入Endpoint后,只需要創(chuàng)建外部服務的Endpoint和Service后糠睡,容器就能通過ServiceName訪問外部服務了挽鞠。
- LoadBalance引入外部服務
Kubernetes開發(fā)的負載均衡器,都有一個優(yōu)點狈孔,能夠實時更新后端容器服務的IP地址信认。基于這點均抽,現(xiàn)公司架構嫁赏,可以利用K8s負載均衡器的特性,將自己傳統(tǒng)的負載均衡器納入到K8s的管理中來到忽。
方案
1. 容器訪問外部獨立服務
- 外部服務的Service橄教,以Mysql為例
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
- 外部服務的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引入外部服務
- 外部服務的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
- 外部服務的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