什么是Headless Services
Headless Services是一种特殊的service,其spec:clusterIP表示为None,这样在实际运行时就不会被分配ClusterIP。也被称为无头服务。
Headless Services使用场景
第一种:自主选择权,有时候client想自己决定使用哪个Real Server,可以通过查询DNS来获取Real Server的信息
第二种:headless service关联的每个endpoint(也就是Pod),都会有对应的DNS域名;这样Pod之间就可以互相访问
基于上面的两个例子,kubernates增加了headless serivces功能,也就是该service对外无提供ClusterIP。下面我们看看它如何配置的:
实例如下:
1: 创建namespace
[root@bogon ~]# vim mysql-space.yaml
apiVersion: v1
kind: Namespace
metadata:
name: mysql-space
labels:
name: mysql-space
2: 创建RC
[root@bogon ~]# vim mysql-rc.yaml
apiVersion: v1
kind: ReplicationController
metadata:
name: mysql-balance-rc
namespace: mysql-space
labels:
name: mysql-balance-rc
spec:
replicas: 2
selector:
name: mysql-balance-pod
template:
metadata:
labels:
name: mysql-balance-pod
spec:
containers:
- name: mysql
image: mysql:5.7
imagePullPolicy: IfNotPresent
ports:
- containerPort: 3308
env:
- name: MYSQL_ROOT_PASSWORD
value: "mysql123"
自动创建了两个pod
[root@bogon ~]# kubectl get pod -n mysql-space
NAME READY STATUS RESTARTS AGE
mysql-balance-rc-h4x6m 1/1 Running 0 5m47s
mysql-balance-rc-jcl67 1/1 Running 0 5m47s
3: 创建Headless service
[root@bogon ~]# vim mysql-service.yaml
apiVersion: v1
kind: Service
metadata:
name: mysql-balance-svc
namespace: mysql-space
labels:
name: mysql-balance-svc
spec:
ports:
- port: 3308
protocol: TCP
targetPort: 3306
clusterIP: None
selector:
name: mysql-balance-pod
没有分配clusterIP
[root@bogon ~]# kubectl get svc -n mysql-space
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
mysql-balance-svc ClusterIP None <none> 3308/TCP 51s
查看详情:
ClusterIP没有了,并且代理两个Endpoints 172.17.0.2:3306,172.17.0.3:3306 这个两个ip就是pod的ip
[root@bogon ~]# kubectl describe svc mysql-balance-svc -n mysql-space
Name: mysql-balance-svc
Namespace: mysql-space
Labels: name=mysql-balance-svc
Annotations: <none>
Selector: name=mysql-balance-pod
Type: ClusterIP
IP: None
Port: <unset> 3308/TCP
TargetPort: 3306/TCP
Endpoints: 172.17.0.2:3306,172.17.0.3:3306
Session Affinity: None
Events: <none>
操作其中一个mysql:
[root@server01 ~]# mysql -h 172.17.0.2 -uroot -pmysql123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.31 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
其实一般headless services一般结合StatefulSet来部署有状态的应用,比如kafka集群,mysql集群,zk集群等。
为什么要用headless service+statefulSet部署有状态应用?
- .headless service会为关联的Pod分配一个域
.$.svc.cluster.local - StatefulSet会为关联的Pod保持一个不变的Pod Name
statefulset中Pod的hostname格式为 (pod序号) - StatefulSet会为关联的Pod分配一个dnsName
.$.svc.cluster.local