Introduction
When working with Kubernetes, one common challenge developers face is handling data persistence. By default, containers are ephemeral, meaning any data stored inside a container is lost when the container is restarted or deleted.
In real-world applications such as databases, logging systems, and file storage services, data must be preserved even if the container lifecycle changes. This is where Kubernetes Persistent Volumes (PV) and Persistent Volume Claims (PVC) come into play.
This article provides a detailed, step-by-step guide on how to configure persistent volumes in Kubernetes, along with explanations, examples, use cases, and best practices.
What is a Persistent Volume (PV)?
A Persistent Volume (PV) is a piece of storage in a Kubernetes cluster that has been provisioned either manually by an administrator or dynamically using a StorageClass.
Key Characteristics of PV
It exists independently of pods
It is managed by Kubernetes
It can be reused across different pods
It supports multiple storage types (NFS, cloud disks, local storage)
Real-World Example
Consider a MySQL database running inside a Kubernetes pod. If the pod crashes and restarts, the data inside the container will be lost unless it is stored in a Persistent Volume.
What is a Persistent Volume Claim (PVC)?
A Persistent Volume Claim (PVC) is a request for storage by a user or application.
Key Characteristics of PVC
It requests specific storage size
It defines access modes
It binds to a matching Persistent Volume
Real-World Analogy
Think of PV as a physical hard drive and PVC as a request to use a portion of that drive.
Kubernetes Storage Architecture
The relationship between components:
PV → Actual storage resource
PVC → Request for storage
Pod → Uses storage via PVC
This separation allows better flexibility and management of storage resources.
Step 1: Create a Persistent Volume (PV)
First, define a Persistent Volume using a YAML configuration file.
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
Code Explanation
capacity: Defines storage size (1Gi)accessModes: Specifies how the volume can be accessedhostPath: Uses local storage from the node
Apply the configuration:
kubectl apply -f pv.yaml
Step 2: Create a Persistent Volume Claim (PVC)
Now create a PVC to request storage.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
Code Explanation
Requests 1Gi storage
Matches PV based on size and access mode
Apply the configuration:
kubectl apply -f pvc.yaml
Join the conversation! Your thoughts help the community grow.