且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Minikube上的Kubernetes StatefulSet中添加持久卷

更新时间:2022-11-30 21:27:22

如果在StatefulSet中使用volumeClaimTemplates,则k8s会进行动态预配置&为每个吊舱创建一个PVC和相应的PV,因此每个吊舱都有自己的存储空间.

If you use volumeClaimTemplates in StatefulSet k8s will do dynamic provisioning & create one PVC and corresponding PV for each pod, so each one of them gets their own storage.

您要创建一个PV&一张PVC,并将其用于Statefulset的所有副本中.

What you want is to create one PV & one PVC and use it in all replicas of Statefulset.

下面是Kubernetes 1.10上的示例,该方法如何实现,所有三个Pod都将共享/var/www/html,只需将/directory/on/host更改为机器上的某个本地目录即可.我也在minikube v0.26.0上运行了这个示例

Below is example on Kubernetes 1.10 how you can do it, where /var/www/html will be shared by all three Pods, just change /directory/on/host to some local directory on your machine. Also I ran this example on minikube v0.26.0

下面的课程当然只是一个示例,但在一个真实的示例中,Pod中的进程应注意同步访问共享存储.

Ofcourse below is just an example to illustrate the idea, but in a real example processes in Pod should be aware of syncronizing access to shared storage.

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: example-pv
spec:
  capacity:
    storage: 100Gi
  # volumeMode field requires BlockVolume Alpha feature gate to be enabled.
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Delete
  storageClassName: local-storage
  local:
    path: /directory/on/host
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values:
                - minikube 
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: example-local-claim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: local-storage
---
apiVersion: "apps/v1beta1"
kind: StatefulSet
metadata:
  name: nginx
spec:
  serviceName: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx-container 
          image: "nginx:1.12.2"
          imagePullPolicy: "IfNotPresent"
          volumeMounts: 
            - name: localvolume
              mountPath: /var/www/html
      volumes:
        - name: localvolume
          persistentVolumeClaim:
            claimName: example-local-claim