Kubernetes PersistentVolumeClaim

A PersistentVolumeClaim (PVC) is a request for storage by a user. It is similar to a Pod. Pods consume Node resources, and PVCs consume PV resources. Pods can request specific levels of resources (CPU and memory). PVCs can request PVs with a specific size and access mode (for example, they can be mounted as read/write once or read-only many times).

Manifest Example

1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-first-pvc
spec:
accessModes:
- ReadWriteOnce
volumeMode: Filesystem
resources:
requests:
storage: 8Gi
storageClassName: hostpath

volumeMode: When requesting storage with a specific access mode, PVCs use the same conventions as PVs.
resources: PVCs use the same conventions as PVs to indicate whether the volume will be used as a filesystem or a block device.
storageClassName: A PVC can request a specific StorageClass by specifying the name of the StorageClass using the storageClassName attribute. Only PVs with the same storageClassName as the PVC can be bound to it.
selector: A PVC can specify a label selector to further filter volumes. Only PVs whose labels match the selector can be bound to the PVC.

Creating a PVC

1
kubectl apply -f https://raw.githubusercontent.com/chengqing-su/kubernetes-learning/master/volumes/pvc-example.yaml

Check the PVC status, as shown below:
pvc

Check the PV status, as shown below:
pv

PVC as Volumes

Pods cannot use PVs directly — they must use PVs through a PVC.

A PVC must exist in the same namespace as the Pod that uses it. The cluster finds the PVC in the Pod’s namespace and uses it to obtain the PersistentVolume backing the PVC. The volume is then mounted to the host and into the Pod.

Create an nginx Pod and use the PVC.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- name: nginx
image: nginx:1.16
ports:
- containerPort: 80
volumeMounts:
- mountPath: /usr/share/nginx/html
name: www-dir
volumes:
- name: www-dir
persistentVolumeClaim:
claimName: my-first-pvc