Search code examples
kuberneteskubernetes-helmpersistent-volumespersistent-volume-claims

Re-use PersistentVolume after re-installing a helm deployment


When I helm delete <deploymentname> a deployment its PVs and PVCs are deleted as well. How can I avoid the actual data in the PVs from being deleted and be able to reclaim those PVs when I helm install <deploymentname> again?

I am using helm upgrade regularly but it makes me very uncomfortable if all it takes to delete all data is a helm delete (even without --purge option it removes all PVs)


Solution

  • If you are looking for persistence between deletion and re-creation, you should not use Deployment but StatefulSet. Stateful sets are something designed to be used for deploying "database-like" applications.

    Stateful sets use persistent pod naming and support generating pvc per pod, also with persistent name. Those pvcs are not deleted when pods/stateful sets are deleted so they remain for reuse by recreated stateful sets or manual release by deleting the pvc(s).

    Example StatefulSet took from https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/ is attached below.

    apiVersion: v1
    kind: Service
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      ports:
      - port: 80
        name: web
      clusterIP: None
      selector:
        app: nginx
    ---
    apiVersion: apps/v1
    kind: StatefulSet
    metadata:
      name: web
    spec:
      serviceName: "nginx"
      replicas: 2
      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" ]
          resources:
            requests:
              storage: 1Gi