How to Create Persistent Volume in Kubernetes: Step-by-Step Guide
To create a
PersistentVolume in Kubernetes, define a YAML manifest specifying storage details like capacity, access modes, and storage class, then apply it using kubectl apply -f. This volume provides durable storage that pods can use independently of their lifecycle.Syntax
A PersistentVolume manifest includes key parts:
- apiVersion: Kubernetes API version, usually
v1. - kind: Must be
PersistentVolume. - metadata: Name and labels for the volume.
- spec: Defines storage details:
capacity: Size of the volume (e.g.,10Gi).accessModes: How pods can access it (e.g.,ReadWriteOnce).persistentVolumeReclaimPolicy: What happens when released (e.g.,Retain).storageClassName: Storage class to use.hostPathor other volume source: Defines actual storage backend.
yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: example-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: manual
hostPath:
path: /mnt/dataExample
This example creates a 10Gi persistent volume using the host's local directory /mnt/data. It can be used by pods with ReadWriteOnce access mode.
yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: local-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: local-storage
hostPath:
path: /mnt/dataOutput
persistentvolume/local-pv created
Common Pitfalls
Common mistakes when creating PersistentVolumes include:
- Using
hostPathvolumes in multi-node clusters without understanding node affinity, causing pods to fail if scheduled on different nodes. - Not matching
storageClassNamebetween PersistentVolume and PersistentVolumeClaim, so claims remain unbound. - Setting incorrect
accessModesthat do not match pod requirements. - Forgetting to set
persistentVolumeReclaimPolicy, which defaults toDeleteand may remove data unexpectedly.
Wrong example:
spec:
storageClassName: fast
accessModes:
- ReadWriteManyRight example:
spec:
storageClassName: fast
accessModes:
- ReadWriteOnceQuick Reference
| Field | Description | Example |
|---|---|---|
| apiVersion | Kubernetes API version | v1 |
| kind | Resource type | PersistentVolume |
| metadata.name | Unique name for the volume | local-pv |
| spec.capacity.storage | Storage size | 10Gi |
| spec.accessModes | Access mode for pods | ReadWriteOnce |
| spec.persistentVolumeReclaimPolicy | Action on release | Retain |
| spec.storageClassName | Storage class name | local-storage |
| spec.hostPath.path | Local path on node | /mnt/data |
Key Takeaways
Define a PersistentVolume with storage size, access modes, and storage class in YAML.
Apply the YAML with kubectl to create the volume in the cluster.
Ensure PersistentVolume and PersistentVolumeClaim storageClassName and accessModes match.
Use hostPath carefully; it ties storage to a specific node.
Set persistentVolumeReclaimPolicy to control volume lifecycle after release.