Post

Volumes

How to configure Kubernetes volumes, PersistentVolumeClaims, and StorageClasses with practical YAML examples.

Volumes

The following pod spec mounts a hostPath volume at /log inside the container, mapping it to /var/log/webapp on the host node. This is useful for persisting log data outside the container lifecycle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cat file.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: webapp
  name: webapp
spec:
  volumes:
  - name: my-volume
    hostPath:
      path: /var/log/webapp
  containers:
  - image: kodekloud/event-simulator
    name: webapp
    resources: {}
    volumeMounts:
    - name: my-volume
      mountPath: /log
  dnsPolicy: ClusterFirst
  restartPolicy: Always

status: {}

Storage classes

This example shows a complete setup including a Pod, PersistentVolumeClaim, and StorageClass. The StorageClass uses WaitForFirstConsumer volume binding mode, which delays volume provisioning until a pod using the PVC is scheduled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
controlplane $ for i in  `ls *.yaml`; do echo "---"; cat $i; done
---
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  volumes:
  - name: from-pvc
    persistentVolumeClaim:
      claimName: local-pvc
  containers:
  - image: nginx:alpine
    name: nginx
    resources: {}
    volumeMounts:
      - name: from-pvc
        mountPath: "/var/www/html"
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: local-pvc
spec:
  storageClassName: local-storage
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 500Mi
---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: delayed-volume-sc
provisioner: kubernetes.io/no-provisioner
parameters:
  type: gp2
reclaimPolicy: Retain
allowVolumeExpansion: true
mountOptions:
  - debug
volumeBindingMode: WaitForFirstConsumer
This post is licensed under CC BY 4.0 by the author.