How to Use a Local Persistent Volume


TL;DR: A local persistent volume in a Kubernetes cluster is a persistent volume allocated in a certain node. Any pod mounting the volume will be automatically scheduled in the same node.

Since it’s limited to 1 node, clearly it can’t be used as a high-availability solution, but hey, it’s quite Ok to use it for experiments in a garage Kubernetes cluster.

Here’s a quick sample to provision a local PV(persistentVolume):

apiVersion: v1
kind: PersistentVolume
metadata:
  name: prometheus-server-local
spec:
  capacity:
    storage: 40Gi
  volumeMode: Filesystem
  # it can only be attached to 1 pod, so...
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  # use this to ensure it being claimed correctly
  claimRef:
    namespace: prometheus
    name: prometheus-server
  # this is the full path in the node
  # I had to created this path myself before I can use it
  local:
    path: /mnt/prometheus-server
  # select where the PV will be scheduled
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values:
                - node7

To claim the PV, the PVC(persistentVolumeClaim) looks like this:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: prometheus-server
  namespace: prometheus
spec:
  # this has to match the one in PV
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: "40Gi"

And that’s it. The PV can be used by a pod now.

apiVersion: v1
kind: Deployment
...
spec:
  replicas: 1
...
      volumes:
        - name: storage-volume
          persistentVolumeClaim:
            claimName: prometheus-server
...

🙂

,