Persistent Volume and Persistent Volume Claim
Concept and Usage of Persistent Volume and Persistent Volume Claim
Refer here (opens in a new tab) for more references.
Persistent volume (PV) is a storage resource in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes. PV has its own lifecycle, that means it does not tied to any pods.
If you want to use a PV in your pod, you need to create a Persistent Volume Claim (PVC) that requests (claims as volumes) a PV with specific storage requirements. The PVC will be bound to a PV that meets the requirements. Remember, PV and PVC are bound together, meaning one PV can only be bound to one PVC. There is one-to-one relationship between PV and PVC, so no other PVC can use the same PV (remaining capacity in the volume).
Create a PV
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-example
labels:
type: fast-storage # label for PV (optional)
spec:
capacity:
storage: 1Gi # reserve 1Gi storage
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
hostPath:
path: /data
Access Mode | Description |
---|---|
ReadWriteOnce | The volume can be mounted as read-write by a single node. ReadWriteOnce access mode still can allow multiple pods to access (read from or write to) that volume when the pods are running on the same node. |
ReadOnlyMany | The volume can be mounted as read-only by many nodes. |
ReadWriteMany | The volume can be mounted as read-write by many nodes. |
ReadWriteOncePod | The volume can be mounted as read-write by a single Pod. Use ReadWriteOncePod access mode if you want to ensure that only one pod across the whole cluster cna read that PVC or write to it. |
Reclaim Policy | Description |
---|---|
Retain | Remain the volume unless it is manually deleted. |
Delete | Delete the volume when the PVC is deleted . |
When you delete a PV, remember to delete the associated PVC first, otherwise, the PV will not be deleted.
Create a PVC
When you create a PVC, Kubernetes will bind the PVC to a PV that meets the requirements. If there is no PV that meets the requirements, the PVC status will remain unbound else it will be bound to a PV.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-example
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
selector: # (optional)
matchLabels:
type: fast-storage # label for PV
selector
is optional, if you want to bind the PVC to a specific PV, you can use theselector
field.
Use PVC in Pod
apiVersion: v1
kind: Pod
metadata:
name: pod-example
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: my-pvc-example # volume name
mountPath: /usr/share/nginx/html
volumes:
- name: my-pvc-example
persistentVolumeClaim:
claimName: pvc-example