Skip to content

Lab 9: Storage & State

Field Value
Tier 2 — Kubernetes Core
Estimated Time 45 minutes
Prerequisites k3s cluster, kubectl
Auto-Grade Yes

Scenario

The data engineering team needs a PostgreSQL instance running on Kubernetes with persistent storage that survives pod restarts. They tried deploying it as a plain Deployment but lost all their data when the pod restarted. They need you to set up a StatefulSet with a PersistentVolumeClaim, seed the database with initial data, verify the data survives a pod deletion, and implement a backup/restore workflow.

The catch: the cluster has a storage class configured, but the PVCs need to be sized correctly. The StatefulSet needs a volumeClaimTemplate. And the backup script needs to use pg_dump inside the pod and copy the dump file to local disk.

Objectives

  • Create a PersistentVolumeClaim pg-data with 1Gi storage
  • Deploy PostgreSQL as a StatefulSet with the PVC mounted at /var/lib/postgresql/data
  • Seed the database with a test table containing at least 5 rows
  • Verify data persists after deleting and recreating the pod
  • Create a backup using pg_dump and store it locally
  • Restore from the backup into a fresh database and verify data

Setup

./setup.sh

Creates namespace lab-storage with a broken PostgreSQL deployment (not StatefulSet).

Hints

Hint 1: StatefulSet volumeClaimTemplates
volumeClaimTemplates:
- metadata:
    name: pg-data
  spec:
    accessModes: ["ReadWriteOnce"]
    resources:
      requests:
        storage: 1Gi
Hint 2: PostgreSQL volume mount Mount the PVC at `/var/lib/postgresql/data` and set the `PGDATA` environment variable to a subdirectory: `PGDATA=/var/lib/postgresql/data/pgdata`.
Hint 3: Seeding data
kubectl exec -n lab-storage pg-0 -- psql -U postgres -c "
  CREATE TABLE IF NOT EXISTS items (id serial PRIMARY KEY, name text);
  INSERT INTO items (name) VALUES ('alpha'),('beta'),('gamma'),('delta'),('epsilon');
"
Hint 4: Backup with pg_dump
kubectl exec -n lab-storage pg-0 -- pg_dump -U postgres > backup.sql
Hint 5: Testing persistence Delete the pod: `kubectl delete pod pg-0 -n lab-storage`. The StatefulSet controller will recreate it. Then check if the data is still there.

Grading

./grade.sh

Solution

See the solution/ directory for StatefulSet manifest and backup scripts.