Sub topic 3
PersistentVolumes: storage as a cluster resource
This chapter assumes you can apply YAML with kubectl and know what Pods and namespaces are. It also assumes you know that a container's filesystem is lost when the container is replaced, and that Pod volumes such as emptyDir live only as long as their Pod.
What a PersistentVolume is
A PersistentVolume (PV) is a cluster-level object that represents a piece of storage. It is not tied to any namespace or Pod. Administrators, or a provisioner acting for them, create PVs. Applications don't use PVs directly. They ask for storage through a claim, which a later chapter covers.
This split separates two roles. The supplier decides where storage comes from and how it behaves. The consumer states how much storage it needs and how it will use it.
A static PV
The manifest below defines a 1Gi volume backed by a directory on a node.
apiVersion: v1
kind: PersistentVolume
metadata:
name: demo-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: manual
hostPath:
path: /mnt/dataEach field has a job:
| Field | Meaning |
|---|---|
| `capacity.storage` | The size of the volume. |
| `accessModes` | How nodes may mount it. `ReadWriteOnce` allows read-write access from a single node. |
| `persistentVolumeReclaimPolicy` | What happens to the volume after its claim is deleted. `Retain` keeps the volume and its data. |
| `storageClassName` | A label that matches claims to this volume. Here `manual` is just a name. |
| `hostPath` | The backing storage, a directory on the node. |
Creating a PV this way is called static provisioning. You make the volumes ahead of time and claims pick from them.
Inspect the volume
Apply the manifest, then list PVs.
kubectl apply -f pv.yaml
kubectl get pvA new PV with no claim shows the status Available. The kubectl get pv command has no namespace flag because PVs are cluster-scoped.
Where the storage comes from
The hostPath field is one volume source. Real clusters usually use a CSI driver, such as the AWS EBS driver, to back PVs with cloud disks or network storage. The PV object looks much the same either way. Later chapters cover CSI drivers and dynamic provisioning, where PVs are created for you.
Common errors
- Looking for a PV with
-n <namespace>. PVs have no namespace, so the flag changes nothing. - Expecting
Retainto make the volume reusable at once. After the claim is deleted, the PV staysReleasedand keeps the old claim reference. An administrator must clean it up before it can bind again. - Using
hostPathon a multi-node cluster and wondering why data differs between Pods.
Exercise
Why is a PV not created inside a namespace, and what does that imply for who manages it?
Show answer
A PV represents storage for the whole cluster, so it is a cluster-scoped object. Administrators or provisioners usually manage PVs, while application teams in each namespace request storage through claims.