一、StatefulSet与Deployment对比
前面提到的Deployment(RC、Deployment、DaemonSet都是常见的无状态服务)用于部署无状态应用,而StatefulSet(有状态的集合)则是用于部署有状态的应用。
无状态应用的特点:
1.可以认为所有Pod都是一样的;
2.Pod的启动没有顺序要求;
3.不用考虑Pod在哪个node运行;
4.可以进行随意的伸缩即扩展。
有状态应用的特点:
1.无状态应用不需要考虑的,有状态都需要考虑;
2.每个Pod独立,保持Pod启动顺序和名称的唯一性;
3.在StatefulSet中,Pod名称叫做网络标识(hostname),持久存储;
4.Pod的启动有序,比如mysql从主、MongoDB集群等。
二、有状态应用的部署
前提条件:需要部署无头服务(headless Service),即在Service中设置ClusterIP: None
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
clusterIP: None
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nginx-statefulset
namespace: default
spec:
serviceName: nginx #声明它属于哪个Headless Service,用来定义Pod网络标识(DNS domain).
replicas: 3
selector:
matchLabels:
app: nginx #has to match .spec.template.metadata.labels
template:
metadata:
labels:
app: nginx #has to match .spec.selector.matchLabels
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
创建有状态的Pod,执行:kubectl apply -f sts.yaml
[root@master-146 ~]# kubectl apply -f sts.yaml
service/nginx created
statefulset.apps/nginx-statefulset created
[root@master-146 ~]# kubectl get pods,svc -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod/nginx-statefulset-0 1/1 Running 0 81s 10.244.1.31 worker-145 <none> <none>
pod/nginx-statefulset-1 1/1 Running 0 61s 10.244.2.30 worker-144 <none> <none>
pod/nginx-statefulset-2 1/1 Running 0 30s 10.244.1.32 worker-145 <none> <none>
pod/web-66bf4959f5-p9dn5 1/1 Running 0 6h38m 10.244.2.25 worker-144 <none> <none>
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 47h <none>
service/nginx ClusterIP None <none> 80/TCP 81s app=nginx
service/web-svc NodePort 10.98.2.183 <none> 80:32192/TCP 107m app=web
1.可以看到有状态的3个Pod的name:pod/nginx-statefulset-0、pod/nginx-statefulset-1、pod/nginx-statefulset-2是唯一的;
2.有状态(StatefulSet)要求Pod名称必须有序,每个Pod不能被随意取代,Pod重建后名称还是同一个。由于Pod重建后Pod的IP是变化的,所以就用Pod名称来唯一识别。
3.无状态(Deployment)的Pod的name后面五位是随机码,是没有顺序的,因此Pod名称是无序的。
StatefulSet有身份唯一标识(域名),格式:
FQDN:$(podname).(headless server name).namespace.svc.cluster.local
nginx-statefulset-0.nginx.default.svc.cluster.local