Persistent volumes

Last modified Apr 20, 2023

Normally when you wish to persist data inside of kubernetes you need to create a volume, and mount it into your container. With StorageClasses it can be done alittle bit smarter. StorageClasses contains a provisioner which is used to automatically provision volumes. So insted of specificing a path somewhere on the host-machine, you create a persistentvolumeclaim, that contains which storageclass that should provision the volume.

Longhorn - How to use?

Longhorn offers such a storageclass mentioned above. Longhorn also do alot of other things with the volumes to ensure availability. Longhorn will automatically replicate all volumes to multiple machines, so in case a host-machine fails, the volume will still be available on other machines. Furthermore Longhorn offers easy ways to create backups of volumes.

1) Creating PersistentVolumeClaim

This means that you can create a persistentvolumeclaim like;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  labels: {}
  name: grafana-claim
  namespace: infrastructure
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: longhorn

When this is applied, the storageClass will use its provisioner to provision the requested volume.

The access modes possible are:

  • ReadWriteOnce – the volume can be mounted as read-write by a single node
  • ReadOnlyMany – the volume can be mounted read-only by many nodes
  • ReadWriteMany – the volume can be mounted as read-write by many nodes
  • ReadWriteOncePod – the volume can be mounted as read-write by a single Pod. This is only supported for CSI volumes and Kubernetes version 1.22+.

2) Mounting volume with PersistentVolumeClaim

When a persistentVolumeClaim are created, you can fx mount it, when creating a deployment like this;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
apiVersion: apps/v1
kind: Deployment
...
spec:
  template:
    spec:
      containers:
        volumeMounts:
          - mountPath: /var/lib/grafana
            name: storage # Needs to match with volume
         volumes:
          - name: storage
            persistentVolumeClaim:
              claimName: grafana-claim