Skip to main content

Containers and Kubernetes · Intermediate · 22 min

Run batch work with Kubernetes Jobs and CronJobs

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kubernetes 1.37 · kind 0.33 · kubeconform 0.8.0

You will run finite work on Kubernetes 1.37 with Jobs that retry, fail fast, time out, clean up after themselves and split work into shards, then schedule it with a CronJob you can pause and trigger by hand.

On this page

A Deployment keeps pods running for ever. Plenty of work is the opposite: resize a batch of images, import yesterday's orders, send a weekly digest, rebuild a search index. That work should start, finish, and report whether it succeeded. Kubernetes runs it with a Job, which creates pods until enough of them have exited with status 0, and a CronJob, which creates a Job on a schedule.

The interesting part is everything around the happy path. What happens when a pod crashes, when the input is bad and retrying is pointless, when a run hangs, when yesterday's run is still going as today's should start? In this tutorial you write a small Job for each of those questions, run them on a kind cluster, and end with a CronJob you would be happy to leave running.

Everything lives in ~/batch-demo on your machine and in a namespace called batch-demo on the cluster. Every Job uses the small busybox:1.37 image. With a tagged image, each node pulls it once and reuses it, which matters if you are working on metered or prepaid data.

Step 1 · Install kubeconform and create the namespace

kubeconform checks manifests against the Kubernetes API schemas before they reach the cluster. It catches a misspelt field such as backofLimit, which a Job would otherwise reject only when you apply it. Install release 0.8.0:

Bash
ARCH="$(dpkg --print-architecture)"
curl -fsSL "https://github.com/yannh/kubeconform/releases/download/v0.8.0/kubeconform-linux-${ARCH}.tar.gz" -o /tmp/kubeconform.tar.gz
sudo tar -xzf /tmp/kubeconform.tar.gz -C /usr/local/bin kubeconform
rm /tmp/kubeconform.tar.gz
kubeconform -v
mkdir -p ~/batch-demo

On macOS, brew install kubeconform does the same. A binary installed by hand gets no updates from apt; to upgrade, run the same commands with the newer version from the project's releases page.

Bash
cat > ~/batch-demo/namespace.yaml <<'YAML'
apiVersion: v1
kind: Namespace
metadata:
  name: batch-demo
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/batch-demo/namespace.yaml
Bash
kubectl apply -f ~/batch-demo/namespace.yaml

Check it worked

kubeconform -v prints v0.8.0, the summary line reads Valid: 1, Invalid: 0, and kubectl get namespace batch-demo shows Active.

Step 2 · Run a Job that completes several pods, two at a time

Two numbers shape a Job. completions is how many pods must succeed before the Job is done. parallelism is how many may run at the same time. Here six units of work run two at a time, so you should see three waves of pods.

You do not have to write a Job from memory. kubectl create job prints a starting manifest without touching the cluster:

Bash
cd ~/batch-demo
kubectl create job process-batch --image=busybox:1.37 -n batch-demo \
  --dry-run=client -o yaml -- sh -c 'echo working' > generated-job.yaml
cat generated-job.yaml

The output has kind: Job, the image, your command, and restartPolicy: Never. A Job's pods may only use Never or OnFailure; the Always that Deployments use would mean the pod never finishes. Use the generated file as a reference and write the full version:

Bash
cat > ~/batch-demo/process-batch.yaml <<'YAML'
apiVersion: batch/v1
kind: Job
metadata:
  name: process-batch
  namespace: batch-demo
spec:
  completions: 6
  parallelism: 2
  ttlSecondsAfterFinished: 300
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: worker
          image: busybox:1.37
          command: ["sh", "-c", "echo \"start $(date +%T) on $HOSTNAME\"; sleep 8; echo done"]
          resources:
            requests:
              cpu: 50m
              memory: 16Mi
            limits:
              memory: 32Mi
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/batch-demo/process-batch.yaml

ttlSecondsAfterFinished: 300 tells the TTL controller to delete the Job, and its pods, five minutes after it finishes. Without it, finished Jobs pile up until someone deletes them. Five minutes is short so you can watch it happen; a day (86400) is a more useful value for real work, because it leaves time to read the logs.

Bash
kubectl apply -f ~/batch-demo/process-batch.yaml
kubectl get pods -n batch-demo -l job-name=process-batch --watch

Press Ctrl+C once six pods show Completed.

Check it worked

While the Job runs, the watch never shows more than two pods Running at once. Then:

Bash
kubectl wait --for=condition=complete job/process-batch -n batch-demo --timeout=120s
kubectl get job process-batch -n batch-demo
kubectl logs -n batch-demo -l job-name=process-batch | grep start

kubectl wait prints condition met, the job row shows 6/6 under COMPLETIONS, and the log lines show three pairs of start times about eight seconds apart. Five minutes later, kubectl get job process-batch -n batch-demo reports NotFound: the TTL controller has removed it.

Step 3 · Decide what a failure means with backoffLimit and podFailurePolicy

By default a Job retries a failed pod up to six times (backoffLimit: 6), waiting 10, 20, 40 seconds and so on between tries, up to six minutes. That suits a flaky network call. It does not suit bad input: if the order file is malformed, the seventh attempt fails exactly like the first, and you have spent several minutes learning nothing.

A podFailurePolicy lets the exit code decide. In the manifest below, every Job shares one policy:

  • Exit code 42 means "the input is bad". FailJob stops the Job at once, with no retries.
  • A pod removed by Kubernetes itself, for example when a node is drained, gets the DisruptionTarget condition. Ignore replaces that pod without counting it against backoffLimit, because the work did not fail.
  • Any other non-zero exit counts as a normal failure, up to backoffLimit: 2.

activeDeadlineSeconds adds a time limit for the whole Job, retries included. It wins over backoffLimit: once the deadline passes, the Job fails and its running pods are stopped.

Write three Jobs that fail in the three different ways. A pod failure policy needs restartPolicy: Never, so the kubelet does not restart the container behind the Job's back:

Bash
cat > ~/batch-demo/failures.yaml <<'YAML'
apiVersion: batch/v1
kind: Job
metadata:
  name: flaky
  namespace: batch-demo
spec:
  backoffLimit: 2
  activeDeadlineSeconds: 180
  podFailurePolicy:
    rules:
      - action: FailJob
        onExitCodes:
          containerName: worker
          operator: In
          values: [42]
      - action: Ignore
        onPodConditions:
          - type: DisruptionTarget
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: worker
          image: busybox:1.37
          command: ["sh", "-c", "echo 'upstream timed out' >&2; exit 1"]
---
apiVersion: batch/v1
kind: Job
metadata:
  name: bad-input
  namespace: batch-demo
spec:
  backoffLimit: 2
  activeDeadlineSeconds: 180
  podFailurePolicy:
    rules:
      - action: FailJob
        onExitCodes:
          containerName: worker
          operator: In
          values: [42]
      - action: Ignore
        onPodConditions:
          - type: DisruptionTarget
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: worker
          image: busybox:1.37
          command: ["sh", "-c", "echo 'orders.csv line 3: missing amount' >&2; exit 42"]
---
apiVersion: batch/v1
kind: Job
metadata:
  name: hangs
  namespace: batch-demo
spec:
  backoffLimit: 2
  activeDeadlineSeconds: 20
  podFailurePolicy:
    rules:
      - action: FailJob
        onExitCodes:
          containerName: worker
          operator: In
          values: [42]
      - action: Ignore
        onPodConditions:
          - type: DisruptionTarget
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: worker
          image: busybox:1.37
          command: ["sh", "-c", "echo 'waiting for a lock'; sleep 600"]
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/batch-demo/failures.yaml

Exit code 42 is a convention you choose, not a Kubernetes rule. Pick codes for your app's "do not retry" cases, document them next to the code, and keep them clear of 137 and 143, which mean the process was killed by a signal.

Bash
kubectl apply -f ~/batch-demo/failures.yaml

Check it worked

Wait a little over a minute, so flaky has used its retries, then read the reason each Job failed:

Bash
kubectl get jobs -n batch-demo \
  -o custom-columns='NAME:.metadata.name,REASON:.status.conditions[?(@.type=="Failed")].reason,FAILED_PODS:.status.failed'

You see something like this:

Text
NAME        REASON                 FAILED_PODS
bad-input   PodFailurePolicy       1
flaky       BackoffLimitExceeded   3
hangs       DeadlineExceeded       1

bad-input stopped after one pod, flaky tried three times (the first run plus two retries), and hangs was stopped at 20 seconds. If flaky has no reason yet, its last retry is still in back-off; run the command again. kubectl describe job bad-input -n batch-demo shows the matching event, naming the rule and the exit code. Delete the three Jobs:

Bash
kubectl delete -f ~/batch-demo/failures.yaml

Step 4 · Split work into shards with an Indexed Job

When work divides into independent pieces, an Indexed Job gives each pod a number. With completionMode: Indexed and completions: 4, Kubernetes runs pods with indexes 0 to 3, sets the JOB_COMPLETION_INDEX environment variable in each, and counts the Job complete once every index has one successful pod. Each pod works out its own slice from that number, so you need no queue or coordinator.

The example adds up the numbers 1 to 1000 in four shards. Swap the loop for "process every customer ID whose number modulo 4 equals my index" and the pattern is the same. Write the script first:

Bash
cat > ~/batch-demo/shard.sh <<'SH'
#!/bin/sh
# Adds up this shard's slice of 1..TOTAL.
set -eu
TOTAL="${TOTAL:-1000}"
SHARDS="${SHARDS:-4}"
INDEX="${JOB_COMPLETION_INDEX:?JOB_COMPLETION_INDEX is not set}"
SIZE=$((TOTAL / SHARDS))
START=$((INDEX * SIZE + 1))
END=$((START + SIZE - 1))
SUM=0
i="$START"
while [ "$i" -le "$END" ]; do
  SUM=$((SUM + i))
  i=$((i + 1))
done
echo "shard $INDEX sum $SUM"
SH

The script assumes TOTAL divides evenly by SHARDS, which 1000 and 4 do. Test it on your machine before it goes anywhere near the cluster, by running every index and adding the results:

Bash
cd ~/batch-demo
for i in 0 1 2 3; do JOB_COMPLETION_INDEX=$i sh shard.sh; done | tee shard-local.txt
awk '{ total += $4 } END { print "total", total }' shard-local.txt

Put the script in a ConfigMap, so the Job can mount it without you building an image:

Bash
cd ~/batch-demo
kubectl create configmap shard-script --from-file=shard.sh -n batch-demo \
  --dry-run=client -o yaml > shard-configmap.yaml
cat > ~/batch-demo/sum-shards.yaml <<'YAML'
apiVersion: batch/v1
kind: Job
metadata:
  name: sum-shards
  namespace: batch-demo
spec:
  completionMode: Indexed
  completions: 4
  parallelism: 2
  backoffLimitPerIndex: 2
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: worker
          image: busybox:1.37
          command: ["sh", "/scripts/shard.sh"]
          env:
            - name: TOTAL
              value: "1000"
            - name: SHARDS
              value: "4"
          volumeMounts:
            - name: scripts
              mountPath: /scripts
              readOnly: true
      volumes:
        - name: scripts
          configMap:
            name: shard-script
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 shard-configmap.yaml sum-shards.yaml

backoffLimitPerIndex: 2 gives each shard its own retry budget. Without it, one bad shard using up a shared backoffLimit would fail the whole Job while the other shards were fine. Keep SHARDS and completions equal; if they drift apart, some numbers are added twice or never.

Bash
kubectl apply -f ~/batch-demo/shard-configmap.yaml -f ~/batch-demo/sum-shards.yaml
kubectl wait --for=condition=complete job/sum-shards -n batch-demo --timeout=120s

Check it worked

Read each pod's index from its annotation, then add up the logs:

Bash
kubectl get pods -n batch-demo -l job-name=sum-shards \
  -o custom-columns='POD:.metadata.name,INDEX:.metadata.annotations.batch\.kubernetes\.io/job-completion-index,STATUS:.status.phase'
kubectl logs -n batch-demo -l job-name=sum-shards | awk '{ total += $4 } END { print "total", total }'

The first table lists four pods with indexes 0, 1, 2 and 3, all Succeeded. The second command prints total 500500, the same as your local run.

Step 5 · Schedule it with a CronJob

A CronJob holds a Job template and a cron schedule, and creates a Job from the template each time the schedule comes round. Generate a starting point as before:

Bash
cd ~/batch-demo
kubectl create cronjob nightly-report --image=busybox:1.37 --schedule='30 2 * * *' -n batch-demo \
  --dry-run=client -o yaml -- sh -c 'date' > generated-cronjob.yaml
cat generated-cronjob.yaml

The generated file has the schedule and a jobTemplate, but none of the settings that make a schedule safe to leave alone. Write the full version:

Bash
cat > ~/batch-demo/nightly-report.yaml <<'YAML'
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
  namespace: batch-demo
spec:
  schedule: "30 2 * * *"
  timeZone: Africa/Lagos
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 600
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 5
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 1800
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: report
              image: busybox:1.37
              command: ["sh", "-c", "echo \"report for $(date -u +%F) generated\""]
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/batch-demo/nightly-report.yaml

What each setting does:

  • timeZone: Africa/Lagos reads the schedule as 02:30 West Africa Time. Without it, the schedule follows the time zone of the kube-controller-manager, which on most clusters is UTC. Use any IANA zone name, such as Africa/Nairobi or Europe/London. Lagos keeps the same offset all year; in a zone with daylight saving, avoid scheduling inside the hour when the clocks change.
  • concurrencyPolicy: Forbid skips a run if the previous one is still going. Allow, the default, lets runs overlap; Replace stops the old run and starts the new one. Reports and imports that write to the same place almost always want Forbid.
  • startingDeadlineSeconds: 600 says a run that cannot start within ten minutes of its time, because the controller was down or the previous run was still going, is skipped rather than started late. It also limits how far back the controller looks for missed runs. Without it, a CronJob that has missed more than 100 schedules stops starting Jobs and logs an error.
  • successfulJobsHistoryLimit and failedJobsHistoryLimit keep the last three good runs and the last five failed ones, so you have logs to read after a bad night. The defaults are 3 and 1. Let these limits tidy up rather than setting ttlSecondsAfterFinished in the template, or the failed runs you want to read may be gone.
  • activeDeadlineSeconds: 1800 in the template stops a hung report after half an hour, so Forbid does not block every later run behind it.

CronJob names can be at most 52 characters, because the controller appends a suffix to make each Job's name.

Bash
kubectl apply -f ~/batch-demo/nightly-report.yaml
kubectl get cronjob nightly-report -n batch-demo

Check it worked

The row shows the schedule 30 2 * * *, SUSPEND as False, and LAST SCHEDULE as <none> until the first run. Confirm the zone was stored:

Bash
kubectl get cronjob nightly-report -n batch-demo -o jsonpath='{.spec.timeZone}{"\n"}'

It prints Africa/Lagos.

Step 6 · Watch Forbid and the history limits on a fast schedule

Waiting for 02:30 is slow, so add a CronJob that fires every minute and deliberately runs for 90 seconds. With Forbid, each run blocks the next schedule, so a new Job should start only every second minute:

Bash
cat > ~/batch-demo/tick.yaml <<'YAML'
apiVersion: batch/v1
kind: CronJob
metadata:
  name: tick
  namespace: batch-demo
spec:
  schedule: "* * * * *"
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 30
  successfulJobsHistoryLimit: 2
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: tick
              image: busybox:1.37
              command: ["sh", "-c", "echo \"tick $(date +%T)\"; sleep 90"]
YAML
kubeconform -strict -summary -kubernetes-version 1.37.3 ~/batch-demo/tick.yaml

startingDeadlineSeconds: 30 makes a skipped minute stay skipped instead of starting late. Keep this value above 10 seconds: the controller checks schedules about every 10 seconds, so a smaller deadline can miss every run.

Bash
kubectl apply -f ~/batch-demo/tick.yaml
kubectl get jobs -n batch-demo --watch

Leave the watch running for about seven minutes, then press Ctrl+C.

Check it worked

Bash
kubectl get jobs -n batch-demo --sort-by=.metadata.creationTimestamp
kubectl describe cronjob tick -n batch-demo | tail -n 15

There are never two tick Jobs running at once, the Job names (tick- followed by the scheduled time in minutes) are about two apart, and no more than two finished tick Jobs are kept, plus the one running now. The events at the end of describe show SuccessfulCreate and SawCompletedJob for each run and SuccessfulDelete as old runs are removed.

Step 7 · Pause a CronJob and run one by hand

Two everyday operations: stop a schedule during an incident or a migration, and run a scheduled Job now instead of waiting for its time.

Suspend tick. A run already in progress carries on; no new ones start:

Bash
kubectl patch cronjob tick -n batch-demo --type=merge -p '{"spec":{"suspend":true}}'
kubectl get cronjob tick -n batch-demo

Runs whose time passes while the CronJob is suspended count as missed. When you resume, a CronJob without startingDeadlineSeconds starts the missed run straight away. nightly-report and tick both set a deadline, so resuming after the deadline has passed just waits for the next time. Keep that in mind before you resume a CronJob that sends emails or charges customers.

Now run the nightly report immediately. kubectl create job --from=cronjob/ copies the CronJob's Job template into a new Job, so you test exactly what will run at 02:30:

Bash
kubectl create job --from=cronjob/nightly-report nightly-report-manual-1 -n batch-demo
kubectl wait --for=condition=complete job/nightly-report-manual-1 -n batch-demo --timeout=60s
kubectl logs -n batch-demo job/nightly-report-manual-1

A manual run ignores concurrencyPolicy, because the CronJob controller does not start it. Check that a scheduled run is not in progress first if overlapping would cause harm.

Check it worked

kubectl get cronjob tick -n batch-demo shows SUSPEND as True, and kubectl get jobs -n batch-demo lists no new tick Jobs from now on. The manual run's log prints a line like report for 2026-11-26 generated. Its annotation shows it was started by hand:

Bash
kubectl get job nightly-report-manual-1 -n batch-demo \
  -o jsonpath='{.metadata.annotations.cronjob\.kubernetes\.io/instantiate}{"\n"}'

It prints manual. To resume the schedule, set suspend back to false with the same patch command.

Step 8 · Clean up

The following deletes the batch-demo namespace and everything in it: both CronJobs, every Job and pod, and the ConfigMap. Make sure you have not put anything else in that namespace before you run it:

Bash
kubectl delete namespace batch-demo

Then remove the local files:

Bash
rm -r ~/batch-demo

Check it worked

kubectl get namespace batch-demo reports NotFound once deletion finishes, and ls ~/batch-demo reports that the folder does not exist. Keep the kind cluster if you are moving on to another Kubernetes tutorial; otherwise remove it with kind delete cluster.

Next steps

  • Compare this with scheduling on a single Linux server, where a systemd timer gives you logs, retries and missed-run handling: /tutorials/replace-cron-jobs-with-systemd-timers.
  • Brush up on the five-field schedule syntax that CronJobs share with cron: /tutorials/schedule-jobs-with-cron.
  • Run a database on the cluster that a nightly Job could back up or report from: /tutorials/run-postgresql-for-snip-in-a-statefulset.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.