How to dynamically create persistent volume claim?

10/22/2019

I am running my application on a bare-metal K8s cluster and I am using an NFS provisioner which takes care of persistent voluems and I just need to create a persitent volume claim. I also have a DB (RethinkDB) on K8s that I am able to cluster and each instance of this DB has its own persistent volume claim and everything is good and working.

My question is: is it possible that I dynamically create persistent volume claims so I can scale my DB similar to kubectl scale deployment registry --replicas=3 without the need that someone create a persistent volume claim for each of these replicas?

My current yaml files:

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

Persistent volume claim:

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
-- AVarf
kubernetes
kubernetes-pvc
persistence
storage

1 Answer

10/22/2019

Deployments are only allowed to have a single PersistantVolumeClaim across all replicas, this is because deployments are designed for effectively stateless services.

You should look at using a 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 for your application including a protection against automatic deletion.

-- robsiemb
Source: StackOverflow