Persistent Volumes on Kubernetes
Setting up a Persistent Volume is necessary for applications requiring a dynamic data store. Pods are temporary, so to provide a method of accessing non-static files (such as uploads, a database, etc.) a form of persistent storage is required.
Some Kubernetes-native clouds provide the ability to allocate storage based on the PersistentVolume configurations, while others will require you to setup your own.
Setup an NFS Server
We'll start by setting up an NFS server on CentOS. This will be straight forward, just a server running an nfs daemon, which you could expand upon with other tools such as block storage or backups.
yum update yum install nfs-server -y mkdir /data echo "/data 192.168.0.0/16(rw, sync, no_squash_root) >> /etc/exports" systemctl start nfs-server systemctl enable nfs-server
A PersistentVolume is storage that is available within the cluster. Kubernetes will look for a PersistentVolume when fulfilling a PersistentVolumeClaim.
Here's an example PersistentVolume configuration.
kind: PersistentVolume apiVersion: v1 metadata: name: example-com-pv labels: app: example-com spec: capacity: storage: 10Gi volumeMode: Filesystem accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Recycle storageClassName: slow mountOptions: - hard - nfsvers=4.1 nfs: path: /data/example-com server: 192.168.0.80
In the above, we've set the capacity of available storage, available accessModes, volumeMode, and nfs settings.
In other words, we've told Kubernetes that there's 10Gig available on this NFS server.
A PersistentVolumeClaim is a request to use a PersistentVolume. It's used by a Pod to access the volume.
kind: PersistentVolumeClaim apiVersion: v1 metadata: name: example-com-pvc labels: app: example-com spec: storageClassName: slow accessModes: - ReadWriteOnce resources: requests: storage: 10Gi
A Pod can now reference the volume and its containers can mount it for use.
kind: Pod apiVersion: v1 metadata: name: example-com labels: app: example-com spec: volumes: - name: example-com persistentVolumeClaim: claimName: example-com containers: - name: example-com image: example/example-com:latest volumeMounts: - mountPath: /var/lib/postgresql/data name: example-com
Review & Recap
PersistentVolumes are references to available storage setup on the cluster. There are several different types available, and in this example we used a seperate NFS server.
PersistentVolumeClaims are individual requests to access PersistentVolumes.
Pods will then reference the claim and mount the volume inside of a container.