This scenario shows how K8s statefulset object works on minikube
- Copy and save (below) as file on your PC (statefulset_nginx.yaml).
- File: https://github.com/omerbsezer/Fast-Kubernetes/blob/main/labs/statefulset/statefulset.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx # create a service with "nginx" name
labels:
app: nginx
spec:
ports:
- port: 80
name: web # create headless service if clusterIP:None
clusterIP: None # when requesting service name, service returns one of the IP of pods
selector: # headless service provides to reach pod with podName.serviceName
app: nginx # selects/binds to app:nginx (defined in: spec > template > metadata > labels > app:nginx)
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web # statefulset name: web
spec:
serviceName: nginx # binds/selects service (defined in metadata > name: nginx)
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: k8s.gcr.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates:
- metadata:
name: www
spec:
accessModes: [ "ReadWriteOnce" ] # creates PVCs for each pod automatically
resources: # hence, each node has own PV
requests:
storage: 512Mi
- Create statefulset and pvc:
- Pods are created with statefulsetName-0,1,2 (e.g. web-0)
- PVCs and PVs are automatically created for each pod. Even if pod is restarted again, same PV is bound to same pod.
- Scaled from 3 Pods to 4 Pods:
- New pod's name is not assigned randomly, assigned in order and got "web-4" name.
- Scale down to 3 Pods again:
- Last created pod is deleted:
- When creating headless service, service does not get any IP (e.g. None)
- With headless service, service returns one of the IP, service balances the load between pods (loadbalacing between pods)
- If we ping the specific pod with podName.serviceName (e.g. ping web-0.nginx), it returns the IP of the that pod.
- With statefulset, the name of the pod is known, this helps to ping pods with name of the pod.