发布时间:2023-09-14 15:00
StatefulSet是用来管理有状态应用的工作负载 API 对象,kubectl中可以简写为sts。sts每个Pod生成一个唯一的标识符 sts_name-number,number从0开始。
StatefulSet会关联卷(volume),删除时不会删除卷,之后PV、PVC的文章中再详细介绍。
StatefulSet需要headless service,需要你去创建该服务,之后service文章中再详细介绍。
StatefulSet不保证Pod数量不为0,顺序创建,倒序删除。
StatefulSet的命名需要遵守 DNS 子域名规范:
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
ports:
- port: 80
name: web
clusterIP: None
selector:
app: nginx
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
selector:
matchLabels:
app: nginx # 必须匹配 .spec.template.metadata.labels
serviceName: "nginx"
replicas: 3 # 默认值是 1
template:
metadata:
labels:
app: nginx # 必须匹配 .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: nginx:1.15.3
ports:
- containerPort: 80
name: web
可以看到创建了nginx的headless service,volumeClaimTemplates通过PV提供存储。
命令
kubectl create -f sts-test.yaml -n killer
kubectl get svc -n killer
kubectl get sts -n killer
kubectl get po -n killer
kubectl get sts web -n killer -o yaml
结果
apiVersion: apps/v1
kind: StatefulSet
metadata:
creationTimestamp: “2022-06-19T16:37:51Z”
generation: 1
name: web
namespace: killer
resourceVersion: “105754”
selfLink: /apis/apps/v1/namespaces/killer/statefulsets/web
uid: 4d7a0d8f-2f44-47ff-a4d7-5100b8be03cd
spec:
podManagementPolicy: OrderedReady
replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
serviceName: nginx
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
containers:
- image: nginx:1.15.3
imagePullPolicy: IfNotPresent
name: nginx
ports:
- containerPort: 80
name: web
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 10
updateStrategy:
rollingUpdate:
partition: 0
type: RollingUpdate
status:
collisionCount: 0
currentReplicas: 3
currentRevision: web-56bf45cc57
observedGeneration: 1
readyReplicas: 3
replicas: 3
updateRevision: web-56bf45cc57
updatedReplicas: 3
命令
kubectl scale sts web --replicas=4 -n killer
通过前面的yaml可以看到更新策略
updateStrategy:
rollingUpdate:
partition: 0
type: RollingUpdate
除了RollingUpdate滚动更新外,还有onDelete在删除时更新。
命令
更新之前,再打开一个终端,运行一个实时查看命令
kubectl get po -l app=nginx -n killer -w
更新命令如下,以修改镜像版本为例
kubectl set image sts web nginx=nginx:latest -n killer --record
命令
kubectl delete po web-1 web-2 -n killer
命令
kubectl delete sts web -n killer
k8s-sts