Skip to content

Latest commit

 

History

History
102 lines (75 loc) · 3.83 KB

K8s-Statefulset.md

File metadata and controls

102 lines (75 loc) · 3.83 KB

LAB: K8s Stateful Set - Nginx

This scenario shows how K8s statefulset object works on minikube

Steps

  • Copy and save (below) as file on your PC (statefulset_nginx.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

image

image

  • Create statefulset and pvc:

image

  • Pods are created with statefulsetName-0,1,2 (e.g. web-0)

image

  • PVCs and PVs are automatically created for each pod. Even if pod is restarted again, same PV is bound to same pod.

image

  • Scaled from 3 Pods to 4 Pods:

image

  • New pod's name is not assigned randomly, assigned in order and got "web-4" name.

image

  • Scale down to 3 Pods again:

image

  • Last created pod is deleted:

image

  • When creating headless service, service does not get any IP (e.g. None)

image

  • With headless service, service returns one of the IP, service balances the load between pods (loadbalacing between pods)

image

  • 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.

image