释放双眼,带上耳机,听听看~!
Service通过标签选择器所关联 Endpoints 后,对客户端来说是透明的,相当于隐藏了EndPoints。
当前有这样的一个Service,ClusterIP为10.110.69.11,Endpoints地址也如下所示
kubectl describe svc nginx-service
Name: nginx-service
Namespace: default
Labels: name=nginx-service
Annotations: Selector: app=nginx
Type: ClusterIP
IP: 10.110.69.11
Port: <unset> 8080/TCP
TargetPort: 80/TCP
Endpoints: 10.244.2.100:80,10.244.3.22:80,10.244.5.144:80
Session Affinity: None
Events: <none>
解析,在我们集群的节点上解析Service的发现名称,如下nginx-service.default.svc.cluster.local
地址解析到了Service的ClusterIP上。
nslookup nginx-service.default.svc.cluster.local
Server: 10.96.0.10
Address: 10.96.0.10#53
Name: nginx-service.default.svc.cluster.local
Address: 10.110.69.11
但是有时候客户端可能有这样的需求,客户端需要直接访问Service资源后端的所有Pod资源,这时就应该向客户端暴露每个Pod资源的IP地址,而不再是中间层'Service'对象的ClusterIP,这种类型的Service便称为 "Headless Service"。
创建Headless Service资源
配置Service资源配置清单时,只需要将ClusterIP字段的值设置为 "None" 即可将其定义为 Headless类型。
at nginx-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
clusterIP: None #指定概属性值为 None 即为 Headless 无头Service
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: nginx-proxy
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deploy
spec:
replicas: 3
selector:
matchLabels:
app: nginx-proxy
template:
metadata:
labels:
app: nginx-proxy
spec:
containers:
- name: nginx-proxy
image: nginx:latest
ports:
- containerPort: 80
name: http
创建资源对象
kubectl apply -f nginx-svc.yaml
查看nginx-service状态
kubectl describe svc nginx-service
Name: nginx-service
Namespace: default
Labels: <none>
Annotations: Selector: app=nginx-proxy
Type: ClusterIP
IP: None #IP地址已经为None
Port: <unset> 80/TCP
TargetPort: 80/TCP
Endpoints: 10.244.2.101:80,10.244.3.23:80,10.244.5.148:80
Session Affinity: None
Events: <none>
通过服务发现地址解析Service,如下解析nginx-service.default.svc.cluster.local
服务发现映射直接映射到了后端的三个Pod地址
nslookup nginx-service.default.svc.cluster.local
Server: 10.96.0.10
Address: 10.96.0.10#53
Name: nginx-service.default.svc.cluster.local
Address: 10.244.2.101
Name: nginx-service.default.svc.cluster.local
Address: 10.244.3.23
Name: nginx-service.default.svc.cluster.local
Address: 10.244.5.148