Jobs and CronJobs

Intermediate · 17 min

Run-to-completion work: Job completions and parallelism, Indexed Jobs, retries and pod failure policies, clean-up, and CronJob schedules, zones and overlap.

Before thisPods in depthControllers and the reconcile loop

Pavan Elthepu · 17 min

Jobs and CronJobs

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Pavan ElthepuReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Job runs Pods until a number of them succeed. completions sets how many, parallelism how many at once, and restartPolicy must be Never or OnFailure.
  • Failed Pods are retried with exponential back-off until backoffLimit; activeDeadlineSeconds caps the whole Job's run time.
  • Indexed Jobs give each Pod a stable index (JOB_COMPLETION_INDEX), so N Pods can split work into N shards. Per-index back-off limits and success policies are GA.
  • podFailurePolicy decides by exit code or Pod condition: fail the Job at once on a bug, ignore a disruption, or count a normal failure.
  • A CronJob creates a Job on a cron schedule, in an optional timeZone. concurrencyPolicy (Allow, Forbid, Replace) decides what happens when the previous run hasn't finished.
  • Make Job work idempotent. A Pod can be retried, and a CronJob can very occasionally start a run twice or skip one.

Work that is meant to stop

Every controller so far keeps Pods running forever. A Deployment that sees a Pod exit successfully starts another, because exiting is failure for a web server. Plenty of work is the opposite: a database migration, a nightly backup, a report, a batch of video encodes, a model training run. Success means the process exits 0, and the right reaction is to stop and record that it finished.

A Job is the controller for that, and a CronJob is a Job factory on a timer.

Jobs

apiVersion: batch/v1
kind: Job
metadata:
  name: report
spec:
  completions: 3
  parallelism: 2
  completionMode: Indexed
  backoffLimit: 4
  ttlSecondsAfterFinished: 3600
  podFailurePolicy:
    rules:
    - action: FailJob            # a config error: retrying won't help
      onExitCodes: {containerName: report, operator: In, values: [42]}
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: report
        image: ghcr.io/example/report:1.3.0
        args: ["--shard=$(JOB_COMPLETION_INDEX)"]

The Job controller creates Pods from the template until completions of them have succeeded, keeping at most parallelism running at once. With neither set, it runs one Pod to success. restartPolicy must be Never (a failed Pod is replaced by a new Pod) or OnFailure (the kubelet restarts the container in place). Pod lifecycle explains the difference.

Failures are retried with an exponential back-off starting at 10 seconds, up to backoffLimit (default 6), after which the Job is marked Failed. activeDeadlineSeconds is a hard cap on the whole Job, retries included. ttlSecondsAfterFinished lets the TTL controller delete a finished Job and its Pods, so they don’t pile up.

Indexed Jobs

With completionMode: Indexed, each Pod gets an index from 0 to completions - 1. The lab Pods were named report-0-..., report-1-..., carried a batch.kubernetes.io/job-completion-index annotation and label, and had an environment variable injected through the downward API:

[{"name":"JOB_COMPLETION_INDEX","valueFrom":{"fieldRef":{"fieldPath":"metadata.labels['batch.kubernetes.io/job-completion-index']"}}}]

Each index must succeed once, and a failed index is retried with the same index, so shard 1 is always shard 1. The lab nodes run no containers, so a script played the kubelet and reported each Pod’s exit code. Index 0 exited 0, index 1 exited 1, then index 2 and the retried index 1 exited 0:

index 0 succeeded:      active=2 succeeded=1 failed=  completedIndexes=0
index 1 failed exit 1:  active=1 succeeded=1 failed=1 completedIndexes=0
after:                  active=1 succeeded=2 failed=1 completedIndexes=0,2   (report-1-bx72z created to retry index 1)
NAME     STATUS     COMPLETIONS   DURATION
report   Complete   3/3           31s

The replacement for index 1 appeared about ten seconds after the failure, the first back-off step. The Job ended with conditions SuccessCriteriaMet and Complete, and completedIndexes=0-2. Indexed Jobs also give each Pod a stable hostname such as report-0, so, with a headless Service, Pods can find each other for distributed training.

Several newer Job fields are now GA: backoffLimitPerIndex so one bad shard doesn’t use up everyone’s retries (1.33), successPolicy to declare success when particular indexes finish (1.33), and podReplacementPolicy: Failed to wait until a failed Pod has fully terminated before replacing it (1.34).

Pod failure policy

Not all failures are equal. A process killed because its node was drained should be retried without counting against the limit. A process that exits 42 because its config is wrong will fail every time. podFailurePolicy (GA in 1.31) matches failed Pods by container exit codes or Pod conditions and picks an action: FailJob, Ignore (don’t count it), Count (the default behaviour) or FailIndex.

The same Job, renamed report-cfg, with one Pod reporting exit code 42:

FailureTarget=True PodFailurePolicy: Container report for pod default/report-cfg-0-khthp failed
                   with exit code 42 matching FailJob rule at index 0
Failed=True        PodFailurePolicy

The Job failed on the first attempt. It went through FailureTarget first and became Failed once its other running Pod had been terminated. The usual pairing is FailJob for your app’s “fatal” exit codes and Ignore for the DisruptionTarget condition, so preemptions and drains don’t burn retries.

CronJobs

apiVersion: batch/v1
kind: CronJob
metadata:
  name: db-backup
spec:
  schedule: "* * * * *"          # every minute, for the demo; nightly would be "30 2 * * *"
  timeZone: Europe/London
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 120
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 1800
      template:
        spec:
          restartPolicy: OnFailure
          containers:
          - name: backup
            image: ghcr.io/example/pg-backup:2.0.0

The CronJob controller checks schedules and creates a Job from jobTemplate at each scheduled time. The lab one created db-backup-29931541, whose suffix is the scheduled time in minutes since the Unix epoch (19:01 UTC), with an annotation recording the scheduled timestamp.

  • schedule uses standard five-field cron syntax, plus macros like @daily.
  • timeZone (GA since 1.27) takes an IANA name. Without it, the schedule follows the controller manager’s clock, usually UTC.
  • concurrencyPolicy decides overlap. Allow (default) runs them side by side, Forbid skips the new run, Replace cancels the old one.
  • startingDeadlineSeconds says how late a run may start, for example after the controller manager was down, before it is counted as missed.
  • History limits keep the last few Jobs for debugging and delete older ones.

Because the lab’s backup Pod never finished, the next minute showed Forbid at work:

75s   Normal   SuccessfulCreate   CronJob/db-backup   Created job db-backup-29931541
15s   Normal   JobAlreadyActive   CronJob/db-backup   Not starting job because prior execution is running and concurrency policy is Forbid

Design for retries

The docs are candid that a CronJob creates a Job “approximately once per execution time”: in rare cases two Jobs can be created, or none. Pods can be retried. So Job work should be idempotent: a backup that writes to a dated path, a migration that checks the schema version, a report that overwrites its output. Pair that with activeDeadlineSeconds so a hung run can’t block every later one under Forbid. Sidecars in Job Pods should be native sidecars so they don’t keep the Pod from completing. For large batch platforms, queueing systems such as Kueue add quotas and fair sharing on top of Jobs.

About the video

The embed is Pavan Elthepu’s “Jobs and CronJobs in Kubernetes” (May 2023, 17 minutes). Its chapters cover why Deployments are wrong for run-once work, the Job lifecycle, CronJobs, use cases, and a hands-on MongoDB backup as a Job and then as a CronJob, with manifests on GitHub. It predates or skips Indexed Jobs, pod failure policies, success policies and per-index back-off, which the lesson adds. English was judged from the “English (US) original” audio track. The Google Cloud Tech video in deeper covers parallel and Indexed Jobs from GKE’s batch team.

What was run: the Indexed Job with its retry and completion, the pod failure policy failing a Job on exit code 42, and the CronJob with its time zone, Job naming and JobAlreadyActive event ran against a local v1.37.3 control plane on 2026-11-28. Its nodes run no containers, so container exit codes were written into Pod status by a script standing in for the kubelet; the Job and CronJob controllers’ reactions were real. GA versions are from the Kubernetes feature-gate reference.

Where this fits

Workloads are covered. Their Pods need configuration that doesn’t belong in the image, which is where the next group starts: ConfigMaps.

Check yourself

  1. 01A Job's container exits with code 42 when its configuration is invalid. How do you stop Kubernetes retrying it six times?

    Add a podFailurePolicy rule with action FailJob and onExitCodes operator In, values [42]. The first such failure marks the Job failed immediately, instead of spending backoffLimit retries on an error that will never go away.

  2. 02Nightly backups run longer than 24 hours for a while, so two overlap and fight over the same lock. Which setting fixes it?

    concurrencyPolicy: Forbid. When the next scheduled time arrives while the previous Job is still active, the CronJob controller skips the run and records a JobAlreadyActive event. Replace would instead kill the old run and start a new one.

  3. 03You need to process 1,000 files with 10 workers, each handling a fixed slice. What Job shape fits?

    An Indexed Job with completions: 10 and parallelism: 10, or more completions than parallelism if you want smaller shards. Each Pod reads JOB_COMPLETION_INDEX to pick its slice, and a failed index is retried with the same index.

  4. 04Your CronJob is scheduled for 02:30 in schedule but the team is in London and the run happens at the wrong hour after the clocks change. What should you set?

    spec.timeZone: Europe/London. Without it the schedule is interpreted in the kube-controller-manager's time zone, usually UTC. With it, the controller handles daylight-saving changes for that zone.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark