Using NFS StorageClass in k8s

Posted on Aug 1, 2024

Connecting to NFS directly with Pod

pod-nfs.yaml

apiVersion: v1
kind: Pod
metadata:
  name: pod-nfs
spec:
  containers:
    - name: pod-nfs
      image: alpine:latest
      command:
        - touch
        - /data/testfile-from-pod-nfs
      volumeMounts:
        - name: nfs-volume
          mountPath: /data
  volumes:
    - name: nfs-volume
      nfs:
        server: 192.168.56.20
        path: /data
        readOnly: no
k create -f pod-nfs.yaml

Check.

ssh 192.168.56.20 'ls -la /data/testfile-from-pod-nfs'

Connecting via PV (PersistentVolume)

nfs-pv.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
spec:
  accessModes:
    - ReadWriteOnce
    - ReadOnlyMany
    - ReadWriteMany
  capacity:
    storage: 3Gi
  storageClassName: ""
  persistentVolumeReclaimPolicy: Recycle
  volumeMode: Filesystem
  nfs:
    server: 192.168.56.20
    path: /data
    readOnly: no
k create -f nfs-pv.yaml 
k get pv

Dynamic provisioning via StorageClass

Official site: https://github.com/kubernetes-sigs/nfs-subdir-external-provisioner

helm repo add nfs-subdir-external-provisioner https://kubernetes-sigs.github.io/nfs-subdir-external-provisioner
helm install nfs-subdir-external-provisioner nfs-subdir-external-provisioner/nfs-subdir-external-provisioner \
    --set nfs.server=192.168.56.20 \
    --set nfs.path=/data \
    --set storageClass.pathPattern='/${.PVC.namespace}-${.PVC.name}'
k get sc

Create PVC.

nfs-pvc.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: nfs-client
  resources:
    requests:
      storage: 1Gi
k create -f nfs-pvc.yaml
k get pvc
k get pv
k get sc

Make a StorageClass as default

For more information, see the documentation: https://kubernetes.io/docs/tasks/administer-cluster/change-default-storage-class/

kubectl patch storageclass nfs-client -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'

Check.

k get sc

Delete a StorageClass

Display the helm’s charts.

helm list

Delete.

helm delete nfs-subdir-external-provisioner

Check.

k get sc