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.

Members can save this page, take notes and track progress. See membership · Sign in

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.

ConfigMap app-configAPP_MODE, LOG_LEVEL, fileSecret db-credentialsbase64, not encryptedPod config-demoenvironment variablesAPP_MODE=…, DB_USER=appvolume /etc/appapp.properties as a fileas envas a fileas envetcdSecrets stored base64Encryption at restKMS provider in productionEnv vars are read once at start; mounted files update when the ConfigMap changes
Configuration reaches a pod as environment variables or as files

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

Download starter filesDownload finished project

Steps

  1. 1A namespace and a ConfigMap

    Keys become environment variables; the multi-line app.properties key 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
    
  2. 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; echo
    

    Expected output

    namespace/data created
    configmap/app-config created
    secret/db-credentials created
    {"password":"UzNjdXJlLWJ1dC1ub3QtZW5jcnlwdGVk","username":"YXBw"}
    S3cure-but-not-encrypted
  3. 3Read the configuration from a pod

    This pod reads two ConfigMap keys and one Secret key as environment variables, and mounts the app.properties key 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
    
  4. 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-demo
    

    Expected 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 logs prints nothing, the pod hasn't finished yet; wait a few seconds and run it again.

  5. 5Check the storage class

    kind ships one StorageClass, standard, using the local-path provisioner. WaitForFirstConsumer means 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). Delete means the volume is removed when its claim is deleted.

    Run
    kubectl get storageclass
    

    Expected output

    NAME                 PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
    standard (default)   rancher.io/local-path   Delete          WaitForFirstConsumer   false                  6m25s
  6. 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 from volumeClaimTemplates. The headless Service gives each pod a stable DNS name. Credentials come from the Secret; the readiness probe waits until Postgres accepts connections.

    Headless Servicepostgres (clusterIP: None)postgres-0postgres-0.postgres.data.svcpostgres-1 (if scaled)postgres-1.postgres.data.svcPVC data-postgres-0always the same claimPVC data-postgres-1its own claimDNS record per pod
    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
    
  7. 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.

    StatefulSet postgresvolumeClaimTemplates: dataPod postgres-0mounts /var/lib/postgresqlPVC data-postgres-01Gi, ReadWriteOnceStorageClass standardprovisioner rancher.io/local-pathPV pvc-88c0f7a1…a folder on the node (cloud: a disk)createsone claim per podmountsasksprovisionsboundDelete the pod: the claim and its data stay. Delete the claim: reclaimPolicy Delete removes the volume.
    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 pv
    

    Expected 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 Bound to a PV, and the PV's CLAIM is data/data-postgres-0.

  8. 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
  9. 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.local
    

    Expected 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 wait says the pod is not found, the StatefulSet hasn't recreated it yet; run wait again.

  10. 10Clean up and watch the volume go

    Deleting the namespace deletes the claim, and the Delete reclaim policy removes the volume with it. In production you would use Retain for important data, and take backups regardless.

    Run
    kubectl delete namespace data
    kubectl get pv
    

    Expected 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

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake