# Storage: data that outlives Pods

Pods are disposable, data is not. Volumes, PersistentVolumeClaims, StorageClasses and the EBS CSI driver, then a StatefulSet where each replica keeps its own disk, all on EKS.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 12. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/12-storage

## What you will learn

- Explain why a container's filesystem is lost with the Pod, and which volumes survive
- Request storage with a PersistentVolumeClaim and see EBS create a real disk
- Write a StorageClass for encrypted gp3 volumes with WaitForFirstConsumer
- Run a StatefulSet where each replica keeps its own volume and name

> **Lab status.** **Verified lab:** a PVC creating a real encrypted EBS gp3 volume, data surviving Pod deletion, and a StatefulSet with one volume per replica, on the course's EKS cluster. The output shown is real. <br />**Code walkthrough:** EFS for shared ReadWriteMany storage (the driver was installed, not used). <br />**Cloud lab:** EBS needs EKS; on kind the built-in `standard` class gives node-local volumes that work the same way for practice.

Everything so far was stateless: kill a shop-web Pod and the new one is identical. A database isn't like that.
Its data has to survive restarts, rescheduling and node failures. This lesson gives Pods real disks.

## Volumes

A container's own filesystem lives and dies with the container. A **volume** is storage mounted into a Pod.
Some kinds are as short-lived as the Pod (`emptyDir`, a scratch directory shared by its containers) or carry
config (`configMap`, `secret`, from lesson 6). For data that must outlive the Pod, the volume points at a
**PersistentVolumeClaim**.

> **Figure.** A Pod named writer with two containers, app and sidecar, each with its own filesystem that is lost on every restart, and three volumes: emptyDir, scratch space shared by both containers and deleted with the Pod; configMap or secret, config files from the API; and the PersistentVolumeClaim notes, the only volume that points outside the Pod, to a PersistentVolume backed by the EBS gp3 disk vol-0a4cf6ce in ap-south-1a. A table shows what survives: the container filesystem survives neither a restart nor a Pod deletion; emptyDir survives a restart only; configMap and secret files come back from the API either way; a PVC survives both.

## StorageClasses and CSI

Kubernetes doesn't make disks itself. A **CSI driver** (Container Storage Interface) talks to the storage
system. The course cluster has two, both EKS add-ons:

```text
$ kubectl get csidrivers
NAME              ATTACHREQUIRED   PODINFOONMOUNT   STORAGECAPACITY   TOKENREQUESTS   REQUIRESREPUBLISH   MODES        AGE
ebs.csi.aws.com   true             false            false             <unset>         false               Persistent   54m
efs.csi.aws.com   false            false            false             <unset>         false               Persistent   60m
```

**EBS** gives block disks attached to one node at a time (`ReadWriteOnce`). **EFS** gives a shared filesystem
many Pods can mount at once (`ReadWriteMany`). A **StorageClass** says which driver to use and how:

```yaml
# 12-storage.yaml (part 1)
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: gp3
provisioner: ebs.csi.aws.com
parameters:
  type: gp3
  encrypted: 'true'
volumeBindingMode: WaitForFirstConsumer # make the disk where the Pod lands
reclaimPolicy: Delete # delete the disk when the claim is deleted
allowVolumeExpansion: true
```

`WaitForFirstConsumer` matters on AWS: an EBS volume exists in one availability zone, and a Pod can only use it
from a node in that zone. Waiting until the Pod is scheduled means the disk is created in the right zone.
`reclaimPolicy: Retain` keeps the disk after the claim is gone, safer for production data.

Here is the whole chain the lab triggered, in order:

> **Figure.** Animation in five steps. 1: the PVC notes, 1Gi ReadWriteOnce class gp3, is applied with the writer Pod and shows Pending. 2: the scheduler places the writer Pod on a node in ap-south-1a. 3: the EBS CSI driver ebs.csi.aws.com calls the EC2 CreateVolume API for that zone. 4: AWS creates vol-0a4cf6ce3523ead79, gp3 and encrypted, in ap-south-1a. 5: the PersistentVolume pvc-b71c5d71 is created and bound to the claim, which turns Bound, and the disk is mounted at /data in the Pod. In the lab the claim was Bound in 13 seconds.

## PersistentVolumes and claims

A Pod asks for storage through a **PersistentVolumeClaim** (PVC): "1Gi, ReadWriteOnce, class gp3". The driver
creates a **PersistentVolume** (PV), the real disk, and binds it to the claim:

```yaml
# 12-storage.yaml (part 2)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: notes
spec:
  accessModes: ['ReadWriteOnce']
  storageClassName: gp3
  resources:
    requests:
      storage: 1Gi
---
apiVersion: v1
kind: Pod
metadata:
  name: writer
spec:
  containers:
    - name: writer
      image: busybox:1.37
      command: ['sh', '-c', 'date >> /data/visits.log; cat /data/visits.log; sleep 3600']
      volumeMounts:
        - name: data
          mountPath: /data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: notes
```

```text
$ kubectl get pvc notes
NAME    STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
notes   Bound    pvc-b71c5d71-baa9-4c8e-81b7-494753c42518   1Gi        RWO            gp3            <unset>                 13s
$ kubectl get pv
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM           STORAGECLASS   ...
pvc-b71c5d71-baa9-4c8e-81b7-494753c42518   1Gi        RWO            Delete           Bound    default/notes   gp3            ...
$ kubectl logs writer
Mon Nov  9 06:45:28 UTC 2026
```

That PV is a real EBS volume in the AWS account, created in 13 seconds:

```text
$ aws ec2 describe-volumes --volume-ids vol-0a4cf6ce3523ead79 --query "Volumes[0].{id:VolumeId,size:Size,type:VolumeType,encrypted:Encrypted,az:AvailabilityZone,state:State}" --output table
|  az        |  ap-south-1a            |
|  encrypted |  True                   |
|  id        |  vol-0a4cf6ce3523ead79  |
|  size      |  1                      |
|  state     |  in-use                 |
|  type      |  gp3                    |
```

Now the test that matters: delete the Pod and start a new one with the same claim.

```text
$ kubectl delete pod writer
pod "writer" deleted from default namespace
$ kubectl apply -f 12-storage.yaml   # recreates the writer Pod
$ kubectl logs writer
Mon Nov  9 06:45:28 UTC 2026
Mon Nov  9 06:46:39 UTC 2026
```

The first line was written by the old Pod, the second by the new one. The data lives on the volume, which
belongs to the claim, not to any Pod. Deleting the **claim** is what deletes the data (with `reclaimPolicy:
Delete`), so treat `kubectl delete pvc` with the same care as dropping a database. And a volume isn't a backup:
take EBS snapshots or use Velero.

> **Figure.** The first writer Pod, now deleted, wrote 06:45:28; the new writer Pod, using the same claim, appended 06:46:39. Both point to the PVC notes, Bound, 1Gi ReadWriteOnce class gp3, bound to PersistentVolume pvc-b71c5d71 with reclaimPolicy Delete, backed by the encrypted EBS gp3 volume vol-0a4cf6ce in ap-south-1a. The file /data/visits.log on the disk holds both lines. Three outcomes below: kubectl delete pod keeps the data; deleting the PVC with reclaimPolicy Delete deletes the PV and the EBS disk; with reclaimPolicy Retain the PV turns Released and the disk stays until you delete it.

## StatefulSets: one disk per replica

A Deployment's replicas are interchangeable and would all share one claim. A database cluster needs each
replica to have **its own** disk and a stable identity. A **StatefulSet** gives both:

> **Figure.** The StatefulSet db with replicas 2 and a volumeClaimTemplate named data, plus a headless Service db that gives each Pod a DNS name, db-0.db and db-1.db. Pod db-0 starts first and uses claim data-db-0, bound to PersistentVolume pvc-2b615ae0 on its own EBS gp3 disk holding I am db-0. Pod db-1 starts after db-0 is Ready and uses claim data-db-1 on its own disk holding I am db-1. On the right: after kubectl delete pod db-0, the StatefulSet makes a new Pod with the same name, which mounts data-db-0 again, and cat /data/id still prints I am db-0. A Deployment would instead share one claim and give Pods random names.

```yaml
# 12-statefulset.yaml (excerpt)
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db # a headless Service gives each Pod a DNS name: db-0.db
  replicas: 2
  template:
    spec:
      containers:
        - name: db
          image: busybox:1.37
          command: ['sh', '-c', 'echo "I am $(hostname)" > /data/id; sleep 3600']
          volumeMounts:
            - name: data
              mountPath: /data
  volumeClaimTemplates: # one PVC per replica: data-db-0, data-db-1
    - metadata:
        name: data
      spec:
        accessModes: ['ReadWriteOnce']
        storageClassName: gp3
        resources:
          requests:
            storage: 1Gi
```

```text
$ kubectl get pods -l app=db -o wide
NAME   READY   STATUS              RESTARTS   AGE   IP       NODE
db-0   0/1     ContainerCreating   0          10s   <none>   ip-10-42-28-149.ap-south-1.compute.internal
$ kubectl get pvc
NAME        STATUS    VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   ...
data-db-0   Bound     pvc-2b615ae0-ad35-4d89-8c27-d51c249b25a1   1Gi        RWO            gp3            ...
data-db-1   Pending                                                                        gp3            ...
$ kubectl exec db-0 -- cat /data/id
I am db-0
$ kubectl exec db-1 -- cat /data/id
I am db-1
$ kubectl delete pod db-0
pod "db-0" deleted from default namespace
$ kubectl exec db-0 -- cat /data/id
I am db-0
```

Three things to notice:

1. Pods start **in order**: db-1 isn't created until db-0 is ready, which is why `data-db-1` was still Pending
   (waiting for its Pod, because of `WaitForFirstConsumer`).
2. Each replica got its **own claim**, named after it.
3. The replacement db-0 came back with the **same name and the same disk**, so it still said "I am db-0".

Deleting a StatefulSet does **not** delete its claims. The lab removed them with `kubectl delete pvc -l app=db`
afterwards, otherwise the EBS volumes keep costing money. In production, most teams run databases on a managed
service (RDS) and keep StatefulSets for things like Kafka, Elasticsearch or caches.

## Mission: Prove the data survives

Create the gp3 StorageClass, a 1Gi claim and the writer Pod. Delete and recreate the Pod twice and record the log. Then run the two-replica StatefulSet, record each replica's /data/id, delete db-0 and record it again. Clean up the claims at the end.

- You need: 12-storage.yaml and 12-statefulset.yaml
- You'll have: ~/storage.txt

```sh
$ kubectl apply -f 12-storage.yaml && kubectl wait --for=condition=Ready pod/writer --timeout=120s
$ for i in 1 2; do kubectl delete pod writer; kubectl apply -f 12-storage.yaml; kubectl wait --for=condition=Ready pod/writer --timeout=120s; done
$ kubectl logs writer > ~/storage.txt
$ kubectl apply -f 12-statefulset.yaml && kubectl rollout status statefulset/db
$ for p in db-0 db-1; do kubectl exec $p -- cat /data/id; done >> ~/storage.txt
$ kubectl delete pod db-0 && kubectl wait --for=condition=Ready pod/db-0 --timeout=120s
$ kubectl exec db-0 -- cat /data/id >> ~/storage.txt
$ kubectl delete -f 12-statefulset.yaml; kubectl delete pvc -l app=db; kubectl delete pod writer; kubectl delete pvc notes
```

The writer log should have three timestamps. On kind, change `storageClassName` to `standard`.

## Try it

- Run `kubectl get csidrivers` and `kubectl get storageclass`.
- Apply the storage manifest and watch the PVC go from Pending to Bound.
- Find the EBS volume behind the PV in the AWS console or CLI.
- Delete the writer Pod, recreate it and check the log has two lines.
- Do the mini mission and keep `~/storage.txt`.

## Quiz

1. You delete a Pod that wrote to a PersistentVolumeClaim and create a new Pod with the same claim. What does it see?
   - An empty disk
   - **The same data; the volume belongs to the claim, not the Pod** (answer)
   - An error
   Why: In the lab the second writer's log showed both the 06:45:28 and 06:46:39 lines.

2. What does volumeBindingMode WaitForFirstConsumer do?
   - Waits for an admin to approve the volume
   - **Delays creating the disk until a Pod using the claim is scheduled, so the disk is made in that Pod's zone** (answer)
   - Makes the volume read-only
   Why: An EBS volume lives in one availability zone. Creating it before the Pod is placed could put it in the wrong zone.

3. Why use a StatefulSet instead of a Deployment for a database?
   - It's faster
   - **Each replica gets a stable name (db-0, db-1) and its own volume that stays with that name across restarts** (answer)
   - Deployments can't use volumes
   Why: After deleting db-0, the new db-0 still read "I am db-0" from its own disk.

## Resources

- [Persistent volumes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/) (Kubernetes)
- [Storage classes](https://kubernetes.io/docs/concepts/storage/storage-classes/) (Kubernetes)
- [StatefulSets](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/) (Kubernetes)
- [Amazon EBS CSI driver](https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html) (AWS Docs)
