An abstract way to expose an application running on a set of Pods as a network service.
With Kubernetes you don’t need to modify your application to use an unfamiliar service discovery mechanism. Kubernetes gives Pods their own IP addresses and a single DNS name for a set of Pods, and can load-balance across them.
简单点一句话就是,Service关联Pod
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
# type 一共有四種(ClusterIP, NodePort, LoadBalancer, ExternalName)
# 預設是 ClusterIP
type: ClusterIP
# 選擇帶有 "app=MyApp" 的 pod
selector:
app: MyApp
# Service 實際對外服務的設定
ports:
- protocol: TCP
port: 80
# 此為 Pod 對外開放的 port number
targetPort: 9376
透過以上的定義,會產生出以下的 network topology:
Pod <---> Endpoint(tcp:9376) <---> Service(tcp:80, with VIP)
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
selector:
app: MyApp
# 透過指定不同的 name 可以清楚知道每個 port 的目的
ports:
- name: http
protocol: TCP
port: 80
targetPort: 9376
- name: https
protocol: TCP
port: 443
targetPort: 9377
但相對的後端的 pod 也要有開放多個 port 才有效果
kind: Service
apiVersion: v1
metadata:
name: my-nodeport-service
spec:
# 將 type 設定為 NodePort
type: NodePort
# 選擇帶有 "app=MyApp" 的 pod
selector:
app: MyApp
# Service 實際對外服務的設定
ports:
- protocol: TCP
port: 80
targetPort: 9376
# 指定 NodePort number(.spec.ports[*].nodePort)
# 也可不指定(30000~32767)
nodePort: 30036
LoadBalancer 公有云上用
Load Balancer type 是另一個讓外部可以直接存取 cluster 內部 service 的方式。
但這個 Service Type 需要與外部的 load balancer 服務搭配,因此目前僅有在 public cloud or OpenStack 上才有支援,但由於我目前都不是在這環境上架設 k8s,因此這個部份就先略過。
ExternalName 设置DNS的CNAME解析
ExternalName 的設定其實就是把 Service 導向指定的 DNS name,而不是 service 中 label selector 所設定的 pod
kind: Service
apiVersion: v1
metadata:
name: my-service
namespace: prod
spec:
type: ExternalName
externalName: my.database.example.com
當 cluster 內部查找 my-service.prod.svc 的時候,k8s DNS service 就只會回應 my.database.example.com 這個 CNAME recrd。
注意! 若要使用 ExternalName,k8s DNS service 的部份僅能安裝 kube-dns,且版本需要是 1.7 以上
iptables 和 ipvs 是Service的2种网络模式
默认用的是iptables
总结来说
ipvs这种四层的模式效率更高一点 ,负载均衡算法比iptables也更优秀,需要安装配置的时候选成ipvs