Kubernetes - Volumes
Disk files for a container is ephemeral. To persist data over container restart, we need to use PersistentVolume
Kubernetes supports many Volume Types
- emptyDir
- azureDisk
- awsElasticBlockStore
- gcePersistentDisk
- …
emptyDir
An emptyDir volume is first created when a Pod is assigned to a Node, and exists as long as that Pod is running on that node. It can be used for Pods to share files.
By default, emptyDir volumes are stored on whatever medium is backing the node - that might be disk or SSD or network storage, depending on your environment.
All containers in a pod can share an emptyDir. emptyDir volume can mount to the same or different path.
emptyDir volume is removed when a Pod is removed.
Example
1 | apiVersion: v1 |
PersistentVolume
For persistent volume use PersistentVolume(PV) and PersistentVolumeClaim(PVC).
- PersistentVolume is usually managed by administrators
- PersistentVolume can be requested by PersistentVolumeClaim
There are three steps to use PersistentVolume.
- Administrator create PersistentVolume
- Developer create PersistentVolumeClaim that claims part of that PersistentVolume disk space
- Developer create pod that that uses PersistentVolumeClaim
Step1: Create PersistentVolume
mongo-pv.yml
1 | apiVersion: v1 |
use kubectl get pv
to display PersistentVolume resources. storageClassName is very important. It is used to tie PersistentVolume and PersistentVolumeClaim. The status is Available at this time. If a PersistentVolumeClaim is bound, the status will be Bound.
3 Access Modes
- ReadWriteOnce: The Volume can be mounted as read-write by a single node.
- ReadOnlyMany: The Volume can be mounted read-only by many nodes.
- ReadWriteMany: The Volume can be mounted as read-write by many nodes. PersistentVolumes that are backed by Compute Engine persistent disks don’t support this access mode.
use kubectl get pv
command to display the PersistentVolumes.
1 | $ kubectl get pv |
Step2: Create PersistentVolumeClaim
mongo-pvc.yml
1 | apiVersion: v1 |
use kubectl get pvc
to display PersistentVolumeClaim
1 | $ kubectl get pvc |
Step3: Create Pod that uses the PersistentVolumeClaim
mongo.yml: defines a service and statefulset that uses PersistentVolume.
1 | apiVersion: v1 |
After the statefulset is created, use kubectl get statefulsets
to check the statefulset status
1 | $ kubectl get statefulsets |
Use kubectl exec -it mongo-0 /bin/bash
to get into the container and use the mongodb database. The data will persiste over pod restart.