Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 3

Lab: Jobs, StatefulSets and persistent volumes

Run PostgreSQL as a single-replica StatefulSet with a headless Service and its own PersistentVolumeClaim, apply a schema change with an idempotent Job, schedule a CronJob safely, and prove that the data survives when the Pod is replaced.

Contentsand lesson path

What you will learn

  • Run batch and stateful workloads with Jobs, CronJobs and StatefulSets backed by PersistentVolumeClaims, and explain what happens to their identity and data when Pods are rescheduled.

Prerequisites: Containerization

01. Goal and setup

Deployments suit services whose replicas are interchangeable. Two other workload types cover the rest: a StatefulSet gives each Pod a stable name, a stable DNS name and its own volume, and a Job or CronJob runs work that should finish rather than serve. In this lab you run all three against one database.

You need the kind cluster from lesson 2 and openssl to generate a password. Image: postgres:18-alpine. The psql output in step 2 comes from a real run of the same SQL on PostgreSQL; everything else from the cluster is illustrative, and long lines are cut with an ellipsis.

Layout
k8s-lab/data/
├── db.yaml       step 1: headless Service and PostgreSQL StatefulSet
├── migrate.yaml  step 2: one-off schema migration Job
└── cron.yaml     step 3: CronJob that records one row per minute

02. Step 1: A StatefulSet with a headless Service

Read db.yaml with these points in mind.

  • Headless Service. clusterIP: None means no virtual IP: DNS returns Pod addresses, and each StatefulSet Pod gets its own record, <pod>.<service>.<namespace>.svc.cluster.local. serviceName must name this Service, which you create yourself; with no such Service, the per-Pod names do not exist.
  • Identity. Pods are named db-0, db-1 and so on. By default they start in order, each one after the previous is Ready, and scale down in reverse.
  • Storage. volumeClaimTemplates creates one PersistentVolumeClaim per Pod, named <template>-<pod>, here data-db-0. A replacement db-0 binds the same claim again.
  • The database itself. The official image refuses to initialise without POSTGRES_PASSWORD, so it comes from a Secret. From PostgreSQL 18 the image keeps its data in /var/lib/postgresql/18/docker, so mount the volume at /var/lib/postgresql. With PostgreSQL 17 and older, mount at /var/lib/postgresql/data and set PGDATA to a subdirectory, because a fresh disk often contains a lost+found folder that makes initialisation fail. The readiness probe uses TCP on 127.0.0.1, so the Pod is not Ready while the image runs its first-start set-up on a local socket.
YAML · data/db.yaml
apiVersion: v1
kind: Service
metadata:
  name: db
spec:
  clusterIP: None  # headless: DNS returns Pod IPs, one name per Pod
  selector:
    app: db
  ports:
    - name: postgres
      port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db  # must name the headless Service above
  replicas: 1
  selector:
    matchLabels:
      app: db
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain  # the default, written out
    whenScaled: Retain
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: docker.io/library/postgres:18-alpine
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef: {name: db-credentials, key: password}
          ports:
            - containerPort: 5432
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres", "-h", "127.0.0.1"]
            periodSeconds: 5
          resources:
            requests: {cpu: 100m, memory: 256Mi}
            limits: {memory: 256Mi}
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql  # PGDATA is 18/docker below it
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 1Gi
Terminal
mkdir -p data && cd data
kubectl create secret generic db-credentials \
  --from-literal=password="$(openssl rand -hex 16)"
kubectl apply -f db.yaml
kubectl rollout status statefulset/db --timeout=180s
kubectl get pods,pvc -l app=db
kubectl get storageclass
Illustrative output
secret/db-credentials created
service/db created
statefulset.apps/db created
Waiting for 1 pods to be ready...
partitioned roll out complete: 1 new pods have been updated...
NAME       READY   STATUS    RESTARTS   AGE
pod/db-0   1/1     Running   0          41s

NAME                              STATUS   VOLUME          CAPACITY   ACCESS MODES   …
persistentvolumeclaim/data-db-0   Bound    pvc-3f2c9a1e…   1Gi        RWO            …
NAME                 PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE    …
standard (default)   rancher.io/local-path   Delete          WaitForFirstConsumer …

kind uses the local-path provisioner: the volume is a folder on the node, and WaitForFirstConsumer delays creating it until the Pod is scheduled, so it lands on the right node. A local volume pins the Pod to that node for good. Cloud block disks such as EBS or Persistent Disk are zonal and ReadWriteOnce: a rescheduled db-0 can only run in the same zone, and stays Pending with a volume node affinity conflict if no node there has room. After a node is lost uncleanly, the old attachment may also have to be released before the disk can attach elsewhere.

03. Step 2: A migration Job that is safe to repeat

A Job runs Pods until they succeed. The fields that matter most:

  • restartPolicy: Never creates a new Pod for each retry, so the logs of failed attempts stay readable; OnFailure restarts the container in the same Pod.
  • backoffLimit caps retries (default 6) with growing delays; then the Job is marked Failed.
  • activeDeadlineSeconds stops a hung Job however many retries remain.
  • ttlSecondsAfterFinished deletes the finished Job and its Pods later, so they do not pile up.

A Job can start a Pod more than once for the same work: a retry after a timeout, or a node lost after the SQL committed but before the Pod reported success. So migrations must be idempotent (safe to run twice) or guarded by a migration tool that records what it applied. CREATE TABLE IF NOT EXISTS is the simplest form. db-0.db resolves through the headless Service.

YAML · data/migrate.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: migrate-001
spec:
  backoffLimit: 4
  activeDeadlineSeconds: 300
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: docker.io/library/postgres:18-alpine
          env:
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef: {name: db-credentials, key: password}
          command:
            - psql
            - --host=db-0.db
            - --username=postgres
            - --set=ON_ERROR_STOP=1
            - --command=CREATE TABLE IF NOT EXISTS beats
                (minute timestamptz PRIMARY KEY)

Run it, then simulate a retry by running it again. A Job runs to completion only once: applying the same manifest again just reports unchanged and starts nothing, and its Pod template cannot be edited after the Job is created (apart from a few scheduling fields while it is suspended). To run it again, delete the Job and create it again.

Terminal
kubectl apply -f migrate.yaml
kubectl wait --for=condition=complete job/migrate-001 --timeout=120s
kubectl logs job/migrate-001
kubectl delete job migrate-001
kubectl apply -f migrate.yaml
kubectl wait --for=condition=complete job/migrate-001 --timeout=120s
kubectl logs job/migrate-001
Illustrative output of the kubectl commands
job.batch/migrate-001 created
job.batch/migrate-001 condition met
job.batch "migrate-001" deleted from default namespace
job.batch/migrate-001 created
job.batch/migrate-001 condition met
Expected output of the two `kubectl logs` commands (psql)
CREATE TABLE
NOTICE:  relation "beats" already exists, skipping
CREATE TABLE

04. Step 3: A CronJob that tolerates its own schedule

A CronJob creates a Job from jobTemplate on a cron schedule. Its safety fields:

  • timeZone makes the schedule explicit; without it, the time zone of kube-controller-manager applies.
  • concurrencyPolicy decides what happens when a run is due while the previous one is still going: Allow (the default) starts another, Forbid skips the new run, Replace stops the old run and starts the new one.
  • startingDeadlineSeconds is how late a missed run may still start, for example after a control plane outage; later than that, the run is skipped. Keep it at 10 seconds or more, because the controller checks schedules about every 10 seconds.
  • successfulJobsHistoryLimit and failedJobsHistoryLimit (defaults 3 and 1) set how many finished Jobs are kept for inspection.

Kubernetes documents that a CronJob creates a Job approximately once per scheduled time: in rare cases it creates two, or none. Forbid prevents overlap, not duplicates. So the work itself must be idempotent: this one inserts a row keyed by the minute and ignores a second insert for the same minute. You can also start a run by hand from the template, which is useful for testing.

YAML · data/cron.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: heartbeat
spec:
  schedule: "* * * * *"
  timeZone: Etc/UTC
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 30
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 50
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: beat
              image: docker.io/library/postgres:18-alpine
              env:
                - name: PGPASSWORD
                  valueFrom:
                    secretKeyRef: {name: db-credentials, key: password}
              command:
                - psql
                - --host=db-0.db
                - --username=postgres
                - --set=ON_ERROR_STOP=1
                - --command=INSERT INTO beats VALUES (date_trunc('minute', now()))
                  ON CONFLICT DO NOTHING
Terminal
kubectl apply -f cron.yaml
kubectl create job --from=cronjob/heartbeat beat-manual
kubectl wait --for=condition=complete job/beat-manual --timeout=60s
kubectl logs job/beat-manual
sleep 150
kubectl get cronjob heartbeat
kubectl get jobs
Illustrative output
cronjob.batch/heartbeat created
job.batch/beat-manual created
job.batch/beat-manual condition met
INSERT 0 1
NAME        SCHEDULE    TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE
heartbeat   * * * * *   Etc/UTC    False     0        31s             2m35s
NAME                 STATUS     COMPLETIONS   DURATION   AGE
beat-manual          Complete   1/1           4s         2m34s
heartbeat-29889240   Complete   1/1           5s         91s
heartbeat-29889241   Complete   1/1           4s         31s
migrate-001          Complete   1/1           6s         4m10s

05. Step 4: Replace the Pod, keep the data

Count the rows, delete db-0, and count again once the new Pod is Ready. The StatefulSet controller recreates a Pod with the same name, which binds the same claim, so the rows are still there; the count only grows, as the CronJob keeps adding one row per minute. The DNS lookup shows the per-Pod name pointing at the new Pod IP.

Terminal
Q='SELECT count(*) AS minutes FROM beats'
kubectl exec db-0 -- psql -U postgres -c "$Q"
kubectl delete pod db-0
kubectl wait --for=create pod/db-0 --timeout=60s
kubectl wait --for=condition=Ready pod/db-0 --timeout=120s
kubectl exec db-0 -- psql -U postgres -c "$Q"
kubectl run dns --rm -i --restart=Never --image=busybox:1.37 -- \
  nslookup db-0.db.default.svc.cluster.local
Illustrative output
 minutes
---------
       3
(1 row)

pod "db-0" deleted from default namespace
pod/db-0 condition met
pod/db-0 condition met
 minutes
---------
       4
(1 row)

Server:    10.96.0.10
Address:   10.96.0.10:53

Name:   db-0.db.default.svc.cluster.local
Address: 10.244.0.27

pod "dns" deleted from default namespace

06. Step 5: What deleting things deletes

Deleting the StatefulSet removes its Pods but, with the default persistentVolumeClaimRetentionPolicy (Retain for both whenDeleted and whenScaled), keeps the claims, so re-creating the StatefulSet would bind the same data. Since Kubernetes v1.32 you can opt in to Delete for either case. Deleting a claim is what removes data: when the PersistentVolume reclaimPolicy is Delete, the default for dynamically provisioned volumes, the volume and its disk go too. Use a StorageClass with Retain, and backups, for data you cannot lose.

Terminal · clean up
kubectl delete cronjob heartbeat
kubectl delete statefulset db
kubectl get pvc
kubectl delete pvc data-db-0
kubectl get pv
Illustrative output
cronjob.batch "heartbeat" deleted from default namespace
statefulset.apps "db" deleted from default namespace
NAME        STATUS   VOLUME          CAPACITY   ACCESS MODES   STORAGECLASS   AGE
data-db-0   Bound    pvc-3f2c9a1e…   1Gi        RWO            standard       9m
persistentvolumeclaim "data-db-0" deleted from default namespace
No resources found

07. Check your understanding

Practice check · 3 questions

Identity, storage and repeated runs

Three questions about this lab.

Q1. A StatefulSet `kafka` with `serviceName: kafka-headless` runs in namespace `stream`. Which name reaches its first Pod from any namespace?
Q2. A nightly CronJob already uses `concurrencyPolicy: Forbid`. After a control plane failover, it ran twice for the same night and charged some customers twice. What would have prevented the double charge?
Q3. The node in zone A that ran `db-0` is gone. Only nodes in zone B have room, and `data-db-0` is a zonal cloud disk in zone A. What happens to the new `db-0`?
Practice only: not graded, not saved, not evidence.

08. Apply it

Toward the skill project:

  • Point the web service from lesson 2 at this database through a Secret, and run the migration Job before each rollout in your pipeline (kubectl wait --for=condition=complete).
  • Write a CronJob that backs up the database with pg_dump to a second PVC, decide its concurrencyPolicy and startingDeadlineSeconds, and restore the dump into a fresh database to prove it works.
  • Compare with the Postgres operator of your choice: which of this lab's manual steps does it automate?

09. Review prompt

Without looking back, explain: what a StatefulSet keeps stable for each Pod and why it needs a headless Service; what happens to a Pod name, its claim and its data when the Pod is deleted, when the StatefulSet is deleted and when the claim is deleted; why a zonal or local volume limits where a Pod can be rescheduled; what backoffLimit, activeDeadlineSeconds and ttlSecondsAfterFinished do; and what concurrencyPolicy and startingDeadlineSeconds control, and why Jobs and CronJobs must still be idempotent.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check