Kubernetes StatefulSetマニフェスト

参考文献: Kubernetesマイクロサービス開発の実践 (早川博 著)

https://qiita.com/ysakashita/items/67a452e76260b1211920

https://zenn.dev/daiskoba/articles/c4ae31ef25657e

 

 

kubectl explain storageclass
kubectl explain persistentvolume
kubectl explain statefulsets

kubectl api-resources

-- 1. workerノードでマウント先のディレクトリ作成

sudo rm -rf /mnt/disks
sudo mkdir -p /mnt/disks/vol{1,2}
sudo chmod 777 /mnt/disks/vol{1,2}

ls -lR /mnt/disks


-- 2. ストレージ作成


cat <<-'EOF' > sc.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: lc01
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
EOF

kubectl apply -f sc.yaml

kubectl get sc


kubectl delete -f sc.yaml


-- 3. PersistentVolume作成

 

cat <<-'EOF' > pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv01
spec:
  capacity:
    storage: 1Gi
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: lc01
  local:
    path: /mnt/disks/vol1
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - mmm162
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv02
spec:
  capacity:
    storage: 1Gi
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: lc01
  local:
    path: /mnt/disks/vol2
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - mmm162

EOF

kubectl apply -f pv.yaml

kubectl get pv

kubectl delete persistentvolumeclaim hoge-sts01-0
kubectl delete persistentvolumeclaim hoge-sts01-1
kubectl delete -f pv.yaml

 

-- 4. StatefulSet作成

cat <<-'EOF' > sts.yaml

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: sts01
spec:
  selector:
    matchLabels:
      app: busybox
  replicas: 2
  template:
    metadata:
      labels:
        app: busybox
    spec:
      containers:
      - name: busybox
        image: busybox
        command: ["/bin/sh","-c"]
        args:
          - |
            while true; do
              echo "$(date -u) / from $(hostname)" >> /data/out.txt
              sleep 5
            done
        volumeMounts:
        - name: hoge
          mountPath: /data
  volumeClaimTemplates:
  - metadata:
      name: hoge
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: lc01
      resources:
        requests:
          storage: 1Gi

 

EOF


kubectl apply -f sts.yaml


kubectl get pod,sc,pv,pvc,sts

cat /mnt/disks/vol1/out.txt
cat /mnt/disks/vol2/out.txt


kubectl exec sts01-0 -- cat /data/out.txt
kubectl exec sts01-1 -- cat /data/out.txt


kubectl delete pod sts01-0

kubectl get pod,sc,pv,pvc,sts


kubectl delete -f sts.yaml