Kubernetes Labs · Lab 3 of 9
ConfigMaps, Secrets and Persistent Storage with a StatefulSet
Feed configuration to a pod as environment variables and files, see why a Secret is only base64-encoded, then run Postgres as a StatefulSet with a persistent volume and prove the data survives when the pod is replaced.
- Environment
- Kubernetes
- Level
- Intermediate
- Time
- About 45 min
- Cost
- Free
You will build
A Postgres StatefulSet whose data lives on a PersistentVolume, configured from a ConfigMap and a Secret, and a clear picture of how a claim, a storage class and a volume fit together.
Before you start
Containers should be the same in every environment; what differs is configuration. Kubernetes keeps it outside the image: a ConfigMap holds plain settings, a Secret holds sensitive ones. Pods read either as environment variables or as files in a volume.
Pods are also disposable, so anything they write inside the container is lost when they are replaced. Durable data goes on a PersistentVolume (PV), requested with a PersistentVolumeClaim (PVC). A StorageClass tells Kubernetes how to create volumes on demand: on kind a folder on the node, on a cloud a network disk.
Every output below was captured from a real run on kind 0.33 with Kubernetes 1.37. Pod names, IP addresses, ages and cluster ports are generated, so yours will differ; everything else should match.
Project structure
config-and-storage/ ├── config.yaml # namespace data + ConfigMap app-config ├── config-demo.yaml # a pod that prints its config from env vars and a file └── postgres.yaml # headless Service + StatefulSet with a volume claim template
Steps
-
1A namespace and a ConfigMap
Keys become environment variables; the multi-line
app.propertieskey will be mounted as a file.config.yaml apiVersion: v1 kind: Namespace metadata: name: data --- apiVersion: v1 kind: ConfigMap metadata: name: app-config namespace: data data: APP_MODE: production LOG_LEVEL: info app.properties: | feature.search=true cache.ttl.seconds=300 -
2Create a Secret, then read it back
Secret values are stored base64-encoded, which is an encoding, not encryption: anyone who can read the Secret can decode it in one command. Protect Secrets with RBAC (lab 9), turn on encryption at rest, and in production keep the real values in a secret manager.
Run kubectl apply -f config.yaml kubectl -n data create secret generic db-credentials --from-literal=username=app --from-literal=password='S3cure-but-not-encrypted' kubectl -n data get secret db-credentials -o jsonpath='{.data}{"\n"}' kubectl -n data get secret db-credentials -o jsonpath='{.data.password}' | base64 -d; echoExpected output
namespace/data created configmap/app-config created secret/db-credentials created {"password":"UzNjdXJlLWJ1dC1ub3QtZW5jcnlwdGVk","username":"YXBw"} S3cure-but-not-encrypted -
3Read the configuration from a pod
This pod reads two ConfigMap keys and one Secret key as environment variables, and mounts the
app.propertieskey as a file. Environment variables are fixed when the container starts; mounted files are updated (within about a minute) when the ConfigMap changes.config-demo.yaml # Reads the ConfigMap two ways: as environment variables and as files in a volume. apiVersion: v1 kind: Pod metadata: name: config-demo namespace: data spec: restartPolicy: Never containers: - name: demo image: busybox:1.38.0 command: ["sh", "-c", "echo APP_MODE=$APP_MODE LOG_LEVEL=$LOG_LEVEL; echo DB user: $DB_USER; cat /etc/app/app.properties"] env: - name: APP_MODE valueFrom: configMapKeyRef: name: app-config key: APP_MODE - name: LOG_LEVEL valueFrom: configMapKeyRef: name: app-config key: LOG_LEVEL - name: DB_USER valueFrom: secretKeyRef: name: db-credentials key: username volumeMounts: - name: config mountPath: /etc/app readOnly: true volumes: - name: config configMap: name: app-config items: - key: app.properties path: app.properties -
4Run it and read its output
Run kubectl apply -f config-demo.yaml kubectl -n data logs config-demo kubectl -n data delete pod config-demoExpected output
pod/config-demo created APP_MODE=production LOG_LEVEL=info DB user: app feature.search=true cache.ttl.seconds=300 pod "config-demo" deleted from data namespace
Hint
If
logsprints nothing, the pod hasn't finished yet; wait a few seconds and run it again. -
5Check the storage class
kind ships one StorageClass,
standard, using the local-path provisioner.WaitForFirstConsumermeans the volume is created only when a pod using it is scheduled, so it lands on the right node (in a cloud: in the right zone).Deletemeans the volume is removed when its claim is deleted.Run kubectl get storageclassExpected output
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE standard (default) rancher.io/local-path Delete WaitForFirstConsumer false 6m25s
-
6Postgres as a StatefulSet
A StatefulSet is for workloads with identity and their own data. Unlike a Deployment, its pods get stable names (
postgres-0,postgres-1…), start in order, and each gets its own PVC fromvolumeClaimTemplates. The headless Service gives each pod a stable DNS name. Credentials come from the Secret; the readiness probe waits until Postgres accepts connections.StatefulSet identity: stable names, stable DNS and a volume per pod postgres.yaml # Headless Service: gives each StatefulSet pod a stable DNS name (postgres-0.postgres.data.svc.cluster.local). apiVersion: v1 kind: Service metadata: name: postgres namespace: data spec: clusterIP: None selector: app: postgres ports: - name: postgres port: 5432 --- apiVersion: apps/v1 kind: StatefulSet metadata: name: postgres namespace: data spec: serviceName: postgres replicas: 1 selector: matchLabels: app: postgres template: metadata: labels: app: postgres spec: containers: - name: postgres image: postgres:18.7-alpine ports: - name: postgres containerPort: 5432 env: - name: POSTGRES_DB value: shop - name: POSTGRES_USER valueFrom: secretKeyRef: name: db-credentials key: username - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: db-credentials key: password volumeMounts: - name: data mountPath: /var/lib/postgresql readinessProbe: exec: command: ["pg_isready", "-U", "app", "-d", "shop"] periodSeconds: 5 resources: requests: cpu: 100m memory: 256Mi limits: memory: 512Mi # One PersistentVolumeClaim per pod (data-postgres-0, data-postgres-1, …), kept when pods are replaced. volumeClaimTemplates: - metadata: name: data spec: accessModes: ["ReadWriteOnce"] resources: requests: storage: 1Gi -
7Apply and follow the claim to the volume
The StatefulSet created the claim
data-postgres-0; the provisioner created a PV for it and bound them.How a StatefulSet pod gets durable storage: claim, class, volume Run kubectl apply -f postgres.yaml kubectl -n data rollout status statefulset/postgres kubectl -n data get statefulset,pods,pvc kubectl get pvExpected output
service/postgres created statefulset.apps/postgres created Waiting for 1 pods to be ready... partitioned roll out complete: 1 new pods have been updated... NAME READY AGE statefulset.apps/postgres 1/1 14s NAME READY STATUS RESTARTS AGE pod/postgres-0 1/1 Running 0 14s NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS VOLUMEATTRIBUTESCLASS AGE persistentvolumeclaim/data-postgres-0 Bound pvc-88c0f7a1-22a3-4fed-8190-ee9c0510b1e1 1Gi RWO standard <unset> 14s NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS VOLUMEATTRIBUTESCLASS REASON AGE pvc-88c0f7a1-22a3-4fed-8190-ee9c0510b1e1 1Gi RWO Delete Bound data/data-postgres-0 standard <unset> 11s
Check:The PVC is
Boundto a PV, and the PV'sCLAIMisdata/data-postgres-0. -
8Write some data
Run kubectl -n data exec postgres-0 -- psql -U app -d shop -c "CREATE TABLE orders (id serial PRIMARY KEY, item text); INSERT INTO orders (item) VALUES ('keyboard'), ('monitor');"Expected output
CREATE TABLE INSERT 0 2
-
9Replace the pod and read the data again
The pod's UID changes, so this really is a new pod, with the same name. It mounted the same claim, so the rows are still there. Its DNS name follows it.
Run kubectl -n data get pod postgres-0 -o jsonpath='{.metadata.uid}{"\n"}' kubectl -n data delete pod postgres-0 kubectl -n data wait pod/postgres-0 --for=condition=Ready --timeout=180s kubectl -n data get pod postgres-0 -o jsonpath='{.metadata.uid}{"\n"}' kubectl -n data exec postgres-0 -- psql -U app -d shop -c 'SELECT * FROM orders;' kubectl -n data run dns-test --rm -i --restart=Never --image=busybox:1.38.0 -- nslookup postgres-0.postgres.data.svc.cluster.localExpected output
770d9728-208f-4585-92c1-22a099886ba3 pod "postgres-0" deleted from data namespace pod/postgres-0 condition met af0658c3-02af-4a08-9a89-f7c926824538 id | item ----+---------- 1 | keyboard 2 | monitor (2 rows) Server: 10.96.0.10 Address: 10.96.0.10:53 Name: postgres-0.postgres.data.svc.cluster.local Address: 10.244.1.15 pod "dns-test" deleted from data namespace
Check:Two different UIDs, the same two rows.
Hint
If
waitsays the pod is not found, the StatefulSet hasn't recreated it yet; runwaitagain. -
10Clean up and watch the volume go
Deleting the namespace deletes the claim, and the
Deletereclaim policy removes the volume with it. In production you would useRetainfor important data, and take backups regardless.Run kubectl delete namespace data kubectl get pvExpected output
namespace "data" deleted No resources found
In production
Running stateful software on Kubernetes is possible and common, but the bar is higher than for stateless apps.
What changes
| In this lab | In production |
|---|---|
Secret created with --from-literal on the command line |
Values in a secret manager (AWS Secrets Manager, Google Secret Manager, Key Vault, Vault) synced by External Secrets Operator or the CSI driver |
| Secrets stored only base64-encoded | Encryption at rest with a KMS key, RBAC that keeps most people and apps from reading Secrets |
| local-path volume on one node | Network disks (EBS, Persistent Disk, Azure Disk) with zone-aware scheduling and snapshots |
reclaimPolicy: Delete |
Retain for important data, plus scheduled backups tested by restoring them |
| One Postgres pod you manage | A managed database (RDS, Cloud SQL, Azure Database), or a Postgres operator (CloudNativePG) for replication, failover and backups |
| Config changes need a manual restart | A config hash or reloader triggers a rollout (lab 5), so changes are visible and reversible |
Should the database run in the cluster?
For most teams, no: a managed database gives you replication, failover, point-in-time recovery and upgrades without building them. Run databases in Kubernetes when you have a reason (cost at scale, portability, an operator you trust) and the skills to operate them. Caches, queues and search indexes that can be rebuilt are easier candidates.
Production checklist
- No secrets in Git, images or ConfigMaps; real values come from a secret manager
- Encryption at rest is on for Secrets, and RBAC limits who can read them
- Every PVC uses a storage class with snapshots or backups, and restores are tested
- Important volumes use
reclaimPolicy: Retain - Stateful pods have requests and limits, readiness probes and a PodDisruptionBudget
- Config changes roll out through the pipeline, never by editing a live ConfigMap
- Databases are managed services unless you have a clear reason and an operator to run them
Learn the concepts
- ConfigMaps · Kubernetes Tutorial
- Secrets · Kubernetes Tutorial
- Persistent Volumes and Claims · Kubernetes Tutorial
- StatefulSets · Kubernetes Tutorial
- Kubernetes in Production · Course
Preparing for the CKA or CKS exam? Practice tests and mock exams →