Stateful Set
tip
The StatefulSet manifest structure is almost identical to Deployment manifest.
- StatefulSet Pods are not anonymous, they have unique identities & unique PVCs.
- Pods are created sequentially, in an order, with sequential pod names
- They get their own PVCs automatically.
- PVCs created by StatefulSets are not deleted automatically on scale-down, only on StatefulSet deletion (if cascade=true).
-
- If the StatefulSet scales back up, it will reuse the exact same PVCs
- Pods running database servers are great fit
Cmds
kubectl get statefulsets # sts
kubectl get pods --field-selector metadata.ownerReferences[0].kind=StatefulSet # filter by owner
How to find them
$ kubectl get sts
# e.g.
NAME READY AGE
web 3/3 10m
$ kubectl get pods -l app=web
StatefulSet Manifest
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: "web"
replicas: 3 # Initial value, HPA will modify
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx
resources:
requests:
cpu: "100m"
limits:
cpu: "500m"
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates: # only for StatefulSets, not for Deployments
- metadata:
name: www
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
storageClassName: standard
Autoscale Stateful Sets
kubectl autoscale statefulset my-stateful-app --cpu-percent=75 --min=3 --max=10
StatefulSet Autoscaler Manifest
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: StatefulSet
name: web
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 75