In the previous post, we learned how to setup an NFS share on a Linux machine. Today, we are going to learn how to mount this share in a Kubernetes cluster.

The first thing we need to define is a PersistentVolume:

persistent-volume.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  name: my-shared-folder-pv
  labels:
    usage: my-shared-folder-pv
spec:
  capacity:
    storage: 50Gi
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Recycle
  nfs:
    server: my-other-server
    path: /var/nfs/my_shared_folder

Then we can create a PersistentVolumeClaim pointing to the volume:

persistent-volume-claim.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-shared-folder-pvc
  annotations:
    volume.beta.kubernetes.io/storage-class: ""
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 50Gi
  selector:
    matchLabels:
      usage: my-shared-folder-pv

We can now deploy these to our Kubernetes cluster:

kubectl apply -f persistent-volume.yaml
kubectl apply -f persistent-volume-claim.yaml

To use it in a deployment, you can mount it now as a volume:

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-server
  labels:
    app: my-server
spec:
  replicas: 1
selector:
    matchLabels:
      app: my-server
  template:
    metadata:
      labels:
        app: my-server
    spec:
      containers:
      - name: my-server
        image: "alpine:3.12"
        command: ["/bin/sh"]
        args: ["-c", "while true; do date >> /mnt/my_shared_folder/dates.txt; sleep 5; done"]
        volumeMounts:
        - name: my-shared-folder
          mountPath: /mnt/my_shared_folder
      volumes:
      - name: my-shared-folder
        persistentVolumeClaim:
          claimName: my-shared-folder-pvc

If you also want to setup the NFS share itself inside the cluster, there are examples available showing you how to do that in the Kubernetes Example repository.