> 文档中心 > K8S statefulset

K8S statefulset

不同于rc、rs、deployment等控制器,statefulset面向的是有状态的服务。创建statefulset后一并与之创建对应的PVC,且每个PVC与创建的pod之间的绑定关系不会随pod的删除而改变,在pod根据replica定义的副本数量再生后,其持久化的数据因此也不会改变。创建后可通过pod.sv.ns的方式来访问,例如web-0.nginx.app01

[root@k8s-master-01 volumeTest]# cat sts.yaml apiVersion: v1kind: Servicemetadata:  name: nginx  labels:    app: nginxspec:  ports:  - port: 80    name: web  clusterIP: None  #声明clusterIP为None  selector:    app: nginx---apiVersion: apps/v1kind: StatefulSetmetadata:  name: webspec:  selector:    matchLabels:      app: nginx # has to match .spec.template.metadata.labels  serviceName: "nginx" #指定无头服务名  replicas: 2 # by default is 1  minReadySeconds: 10 # by default is 0  template:    metadata:      labels: app: nginx # has to match .spec.selector.matchLabels    spec:      terminationGracePeriodSeconds: 10      containers:      - name: nginx image: nginx imagePullPolicy: IfNotPresent ports: - containerPort: 80   name: web volumeMounts: - name: www   mountPath: /usr/share/nginx/html  volumeClaimTemplates:  - metadata:      name: www    spec:      accessModes: [ "ReadWriteOnce" ]      storageClassName: "nfssc"  #使用之前定义过的StorageClass作为存储。      resources: requests:   storage: 1Gi#应用该sts文件过,查看PVC以及pod状态,可见自动创建了pvc[root@k8s-master-01 volumeTest]# kubectl get pvcNAME STATUS   VOLUME  CAPACITY   ACCESS MODES   STORAGECLASS   AGEwww-web-0   Bound    pvc-7410035a-01ae-46a4-8cd2-31745492aef9   1Gi RWO     nfssc   91swww-web-1   Bound    pvc-ee7695d0-6a1d-4650-87f2-b68c7bdbf53e   1Gi RWO     nfssc   51s[root@k8s-master-01 volumeTest]# kubectl get podsNAME    READY   STATUS    RESTARTS   AGEdbpod   1/1     Running   0   4h21mweb-0   1/1     Running   0   95sweb-1   1/1     Running   0   55s#删除上述pods[root@k8s-master-01 volumeTest]# kubectl delete pod web-{0,1}pod "web-0" deletedpod "web-1" deleted#删除后pods再生,pod名字保持不变且根据其age时间可知创建顺序也没有变化。而不同于deployement的同时创建。[root@k8s-master-01 volumeTest]# kubectl get podsNAME    READY   STATUS    RESTARTS   AGEdbpod   1/1     Running   0   4h29mweb-0   1/1     Running   0   24sweb-1   1/1     Running   0   4s#查看创建的svc[root@k8s-master-01 volumeTest]# kubectl get svcNAME    TYPE CLUSTER-IP      EXTERNAL-IP   PORT(S) AGEmysvc   NodePort    10.96.179.103    80:31524/TCP   2d20hnginx   ClusterIP   None      80/TCP  12m#创建一个testpod通过nslookup的方式访问服务,访问方式为“pod名.svc名”[root@k8s-master-01 volumeTest]# kubectl run testpod --image=busybox:1.28 \--image-pull-policy=IfNotPresent -it/ # nslookup web-0.nginxServer:    10.96.0.10Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.localName:      web-0.nginxAddress 1: 10.244.1.51 web-0.nginx.app01.svc.cluster.local