如何动态创建持久卷声明?

How to dynamically create persistent volume claim?

我是 运行 我在裸机 K8s 集群上的应用程序,我正在使用 NFS 配置器来处理持久卷,我只需要创建一个持久卷声明。我在 K8s 上也有一个数据库 (RethinkDB),我可以对其进行集群,并且该数据库的每个实例都有自己的持久卷声明,一切都很好并且可以正常工作。

我的问题是:我是否可以动态创建持久卷声明,以便我可以像 kubectl scale deployment registry --replicas=3 一样扩展我的数据库,而不需要有人为每个副本创建持久卷声明?

我当前的 yaml 文件:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: registry-slave
  labels:
    io.kompose.service: registry-slave
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: registry-slave
  template: # pod template
    metadata:
      labels:
        app: registry-slave
        io.kompose.service: registry-slave
    spec:
      containers:
      - name: registry-slave
        image: rethinkdb:2.3.6
        command: ["rethinkdb"]
        args:
        - --bind
        - "all"
        - --no-update-check
        - --join
        - "registry:29015"
        - --canonical-address
        - "$(MY_POD_IP):29015"
        volumeMounts:
        - name: rdb-local-data
          mountPath: /rethinkdb_data
        env:
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
      volumes:
      - name: rdb-local-data
        persistentVolumeClaim:
          claimName: registry-slave-claim
      restartPolicy: Always

持久卷声明:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: registry-slave-claim
  namespace: {{ .Release.Namespace }}
  annotations:
    volume.beta.kubernetes.io/storage-class: nfs-client
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 500Mi

部署只允许在所有副本中有一个 PersistantVolumeClaim,这是因为部署是为有效的无状态服务而设计的。

您应该考虑为您的应用程序使用 StatefulSet which is the Kubernetes way to deploy stateful applications based on templates. StatefulSets can include a volumeClaimTemplate where one PVC is created per replica. This will provide stable storage,包括防止自动删除的保护。