
Setting up and using an NFS share in Kubernetes
10 Dec 2020 #kubernetes #deployment #linux
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: v1kind: PersistentVolumemetadata: name: my-shared-folder-pv labels: usage: my-shared-folder-pvspec: 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: v1kind: PersistentVolumeClaimmetadata: 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.yamlkubectl apply -f persistent-volume-claim.yaml
To use it in a deployment, you can mount it now as a volume:
deployment.yaml
apiVersion: apps/v1kind: Deploymentmetadata: name: my-server labels: app: my-serverspec: replicas: 1selector: 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.