Skip to content
LF Cert Trainer

Lesson 61 · Section 5: Application Lifecycle Management

Lesson 61: Jobs: run a task to completion

How a Job runs Pods until enough succeed, what completions, parallelism, backoffLimit, activeDeadlineSeconds and ttlSecondsAfterFinished do, Indexed Jobs, Pod failure policies, and how to create and debug a Job fast in the exam. · 19 min read · 3 min video

1/9Jobs
0:00 / 3:15

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why Jobs exist

Most of what you have run so far is meant to run forever. A web server in a Deployment should be up all day, and if its process exits, Kubernetes starts it again. Plenty of real work is different: it has an end.

Kind of taskExamples
One-off maintenanceA database schema migration, re-indexing a search engine, rotating a key
Batch processingResizing a folder of images, importing a CSV file, rendering a report
Scheduled work (with a CronJob, next lesson)A nightly backup, a weekly clean-up, an hourly export

A Deployment cannot run such a task. Its Pods have restartPolicy: Always, so a container that finishes with success is started again, and the task runs in a loop. A bare Pod with restartPolicy: Never runs once, but nothing creates it again if it fails or if its node disappears.

A Job fills that gap. It creates Pods, watches how they end, retries the ones that fail, and stops once enough of them have succeeded.

A Job retries until it has its successestry 1try 21 of 1Job db-migratecompletions: 1Pod db-migrate-4xk2pError, exit 1Pod db-migrate-9tmzqCompleted, exit 0Job conditionComplete
A Job retries until it has its successes. The Job creates a Pod. When the Pod fails, the Job creates a new one after a back-off delay. When enough Pods have succeeded, the Job is marked Complete and creates no more Pods. The Pods stay behind so you can read their logs.

Parts:

  • Job db-migrate (completions: 1)
  • Pod db-migrate-4xk2p (Error, exit 1)
  • Pod db-migrate-9tmzq (Completed, exit 0)
  • Job condition (Complete)

Connections:

  • Job db-migrate to Pod db-migrate-4xk2p: try 1
  • Job db-migrate to Pod db-migrate-9tmzq: try 2
  • Pod db-migrate-9tmzq to Job condition: 1 of 1

What a Job is made of

apiVersion: batch/v1
kind: Job
metadata:
  name: db-migrate
spec:
  backoffLimit: 3                  # failures accepted before the Job fails (default 6)
  activeDeadlineSeconds: 300       # the whole Job may run at most 5 minutes
  ttlSecondsAfterFinished: 600     # delete the Job and its Pods 10 minutes after it ends
  template:
    spec:
      restartPolicy: Never         # Never or OnFailure, never Always
      containers:
        - name: migrate
          image: busybox:1.36
          command: ["sh", "-c", "echo migrating; sleep 5; echo done"]

The Pod template is the same as in a Deployment, with one rule: restartPolicy must be Never or OnFailure. The API server rejects Always, and since the Pod default is Always, you always write this line (kubectl create job writes it for you).

Two things are not needed, unlike a Deployment: a selector and template labels. The Job controller adds a unique label to its Pods (batch.kubernetes.io/controller-uid) and a readable one (job-name and batch.kubernetes.io/job-name), and builds the selector itself. Writing your own selector is possible (manualSelector: true) but almost never wanted.

The fields that make a Job a Job all live in spec, next to the template:

FieldDefaultMeaning
completions1How many Pods must succeed for the Job to be complete
parallelism1How many Pods may run at the same time
backoffLimit6How many failed Pods (or container restarts with OnFailure) before the Job fails
activeDeadlineSecondsnoneThe longest the Job may run, counted from its start; then it fails
ttlSecondsAfterFinishednoneSeconds after the Job finishes (Complete or Failed) before it is deleted with its Pods
completionModeNonIndexedIndexed gives each Pod a number from 0 to completions - 1
suspendfalsetrue stops creating Pods and deletes running ones; false resumes
podFailurePolicynoneRules that decide, per exit code or Pod condition, whether a failure counts, is ignored or fails the Job at once

kubectl get jobs shows the state in a few columns:

ColumnMeaning
STATUSRunning, Complete, Failed or Suspended
COMPLETIONSSuccessful Pods out of completions, for example 3/5
DURATIONFrom start to finish, or until now

How it works: the Job controller counts

Like every workload, a Job is only a record. The Job controller inside kube-controller-manager does the work. It watches Jobs and the Pods they own, and on every change it compares what it has with what it wants:

  1. Count Pods: active, succeeded, failed
  2. Succeeded = completions? Mark Complete, stop
  3. Failed > backoffLimit or deadline passed? Mark Failed, stop Pods
  4. Active < parallelism and successes still missing? Create Pods
  5. Write the counts to status
One pass of the Job controller

A Pod succeeds when all its containers exit with code 0. It fails when a container exits with any other code (with restartPolicy: Never), or when the Pod is lost: evicted, its node gone, deleted by hand.

Retries and the back-off delay

After a failure the controller does not create the next Pod at once. It waits 10 seconds, then 20, then 40, doubling up to a cap of 6 minutes. That keeps a broken task from hammering a database every second. With the default backoffLimit: 6 a Job that always fails takes several minutes before it gives up, which is worth knowing when you are waiting for it in the exam.

Never or OnFailure: who does the retrying

The two allowed restart policies split the retrying between two components:

restartPolicyWhen the container failsWhat you seeCounted against backoffLimit
NeverThe Pod fails; the Job controller creates a new PodSeveral Pods, Error on the failed onesEach failed Pod
OnFailureThe kubelet restarts the container in the same PodOne Pod with a growing RESTARTS count, CrashLoopBackOffEach restart

Never is easier to debug, because every failed attempt keeps its own Pod and its logs. With OnFailure the logs of earlier attempts are gone except for the previous one (kubectl logs --previous). When a task says nothing, use Never.

Three ways a Job gives upJob reportrunningRetries used upBackoffLimitExceededToo slowDeadlineExceededRule matchedPodFailurePolicyJob conditionFailed
Three ways a Job gives up. A Job fails when it has used up its retries (backoffLimit), when it has run longer than activeDeadlineSeconds, or when a Pod failure policy rule says FailJob. In every case running Pods are stopped and the Job gets the condition Failed with a reason.

Parts:

  • Job report (running)
  • Retries used up (BackoffLimitExceeded)
  • Too slow (DeadlineExceeded)
  • Rule matched (PodFailurePolicy)
  • Job condition (Failed)

Connections:

  • Job report to Retries used up
  • Job report to Too slow
  • Job report to Rule matched
  • Retries used up to Job condition
  • Too slow to Job condition
  • Rule matched to Job condition

activeDeadlineSeconds wins over backoffLimit: a Job with a deadline of 60 seconds fails after 60 seconds even if it has retries left. Note that it sits in two places with two meanings. In the Job spec it limits the whole Job. In the Pod template spec it limits each Pod. Tasks almost always mean the Job one.

Under the hood · How the controller knows a Pod was counted: finalizers

A Job may delete its finished Pods (a TTL, or you running kubectl delete pod). If the controller only counted the Pods that exist, a deleted successful Pod would be forgotten and run again. To avoid that, the controller puts the finalizer batch.kubernetes.io/job-tracking on every Pod it creates. It removes the finalizer only after it has added that Pod to the Job's status.succeeded or status.failed. Only then can the Pod really go away.

So the counts in status are the truth, not the list of Pods. If you see a finished Job Pod stuck in Terminating, the controller has not counted it yet, usually because kube-controller-manager is not running.

Parallel Jobs

completions and parallelismcountsJob thumbnailscompletions 5, parallel 2Pod 1CompletedPod 2CompletedPod 3CompletedPod 4RunningPod 5RunningCOMPLETIONS3/5
completions and parallelism. completions is how many Pods must succeed in total; parallelism is how many may run at the same time. With 5 and 2, the Job runs two Pods, starts a new one each time one finishes, and is done after the fifth success.

Parts:

  • Job thumbnails (completions 5, parallel 2)
  • Pod 1 (Completed)
  • Pod 2 (Completed)
  • Pod 3 (Completed)
  • Pod 4 (Running)
  • Pod 5 (Running)
  • COMPLETIONS (3/5)

Connections:

  • Job thumbnails to Pod 1
  • Job thumbnails to Pod 2
  • Job thumbnails to Pod 3
  • Job thumbnails to Pod 4
  • Job thumbnails to Pod 5
  • Pod 3 to COMPLETIONS: counts

completions and parallelism together give three common shapes:

ShapecompletionsparallelismBehaviour
One task1 (default)1 (default)One Pod at a time until one succeeds
Fixed number of tasksN1 to NRuns up to parallelism Pods; complete after N successes
Work queueunsetNRuns N Pods that take work from a queue; complete when one succeeds and all have stopped

The work queue shape needs the application's help: each Pod pulls items from a queue (Redis, RabbitMQ) and exits with success when the queue is empty. The Job then stops creating Pods after the first success and waits for the others to finish.

parallelism can be changed on a running Job (kubectl scale does not work on Jobs, but kubectl patch or kubectl edit does), and setting it to 0 pauses the Job without deleting it. completions cannot be changed, except on an Indexed Job.

Indexed Jobs: each Pod gets a number

With a plain fixed-count Job, all Pods are interchangeable: the fifth success could come from any Pod. Often each Pod should do a different part of the work: file 0, file 1, file 2. That is completionMode: Indexed:

apiVersion: batch/v1
kind: Job
metadata:
  name: render
spec:
  completions: 3
  parallelism: 3
  completionMode: Indexed
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: render
          image: busybox:1.36
          command: ["sh", "-c", "echo rendering chapter $JOB_COMPLETION_INDEX"]

Each Pod gets its index in the environment variable JOB_COMPLETION_INDEX, in the annotation batch.kubernetes.io/job-completion-index and in its name (render-0-x7k2p, render-1-...). The Job is complete when every index has one successful Pod. A failed index is retried with the same number. Pods of an Indexed Job also get a stable hostname (render-0), so with a headless Service they can find each other, which is how some distributed training jobs start.

Two related fields refine the failure rules for Indexed Jobs: backoffLimitPerIndex gives each index its own retry budget, and maxFailedIndexes fails the whole Job once too many indexes have failed.

Choosing which failures count: Pod failure policy

By default every failure costs one retry. That is wasteful when the exit code already says that retrying cannot help (bad input, a bug), and unfair when the Pod was only evicted because its node was drained. podFailurePolicy sorts failures by rules, checked in order:

spec:
  backoffLimit: 6
  podFailurePolicy:
    rules:
      - action: FailJob                # exit code 42 means "bad input": stop at once
        onExitCodes:
          containerName: import
          operator: In
          values: [42]
      - action: Ignore                 # evicted by a drain or preemption: retry for free
        onPodConditions:
          - type: DisruptionTarget
  template:
    spec:
      restartPolicy: Never             # required with podFailurePolicy
      containers:
        - name: import
          image: busybox:1.36
          command: ["sh", "-c", "exit 42"]
ActionEffect
FailJobThe Job fails at once with reason PodFailurePolicy; running Pods are stopped
IgnoreThe failure is not counted against backoffLimit; a replacement Pod is created
CountThe default behaviour: counts as one failure
FailIndexIndexed Jobs with backoffLimitPerIndex only: fail just this index

A Pod failure policy needs restartPolicy: Never, because with OnFailure the kubelet restarts containers before the controller ever sees a failed Pod.

Cleaning up

A finished Job is not deleted. It stays, with its Pods, so you can read the logs. That is useful for a while and clutter after that. Three ways to clean up:

WayHow
Automatic, per JobttlSecondsAfterFinished: 600 in the Job spec. The TTL-after-finished controller deletes the Job and its Pods 10 minutes after it is Complete or Failed. 0 deletes right away.
Automatic, for scheduled JobsA CronJob keeps only its last few Jobs (next lesson)
By handkubectl delete job db-migrate deletes the Job and, through the owner references, its Pods

Changing a Job

Most of a Job is fixed once it is created. The Pod template is immutable: kubectl edit on the image or the command is rejected with field is immutable. That is on purpose, because a Job with half its Pods made from one template and half from another would have no clear meaning. The way to change a Job is to delete it and create it again:

kubectl get job db-migrate -o yaml > job.yaml     # or use the file you created it from
kubectl delete job db-migrate
# edit job.yaml: change the template, remove status, uid, resourceVersion and the generated labels and selector
kubectl apply -f job.yaml

kubectl replace --force -f job.yaml does the delete and create in one step. When you start from kubectl get -o yaml, remove the selector and the controller-uid labels the controller added, or the new Job is rejected for using a selector of its own.

What can change on an existing Job: parallelism, suspend, ttlSecondsAfterFinished, labels and annotations (and, on an Indexed Job whose completions equals its parallelism, both of them together).

Job or something else?

You wantUse
A task that runs once until it succeedsJob
The same task on a scheduleCronJob (next lesson), which creates Jobs
A process that runs all the timeDeployment
A task once on every nodeA DaemonSet, removed afterwards; a Job cannot target "each node"
Setup before the main container starts, inside one PodAn init container (lesson on init containers)

Using it

Example · Run a one-off task and read its output

The task: "create a Job pi that computes pi to 200 digits with the image perl:5.40, and save the output to /opt/pi.txt".

kubectl create job pi --image=perl:5.40 -- perl -Mbignum=bpi -wle 'print bpi(200)'
kubectl get job pi -w                       # wait until COMPLETIONS shows 1/1, then Ctrl+C
kubectl logs job/pi > /opt/pi.txt

kubectl wait --for=condition=complete job/pi --timeout=120s waits without watching by eye, and returns an error if the Job does not finish in time.

Example · A Job with completions, parallelism and a retry limit

The task: "create a Job thumbnails in namespace media that runs the image busybox:1.36 with the command sleep 3. It must succeed 5 times, run at most 2 Pods at once, and give up after 2 failures".

kubectl -n media create job thumbnails --image=busybox:1.36 \
  --dry-run=client -o yaml -- sleep 3 > thumbnails.yaml

Add three lines under spec, at the same level as template:

spec:
  completions: 5
  parallelism: 2
  backoffLimit: 2
  template:
    ...
kubectl apply -f thumbnails.yaml
kubectl -n media get pods -l job-name=thumbnails -w   # never more than two Running at a time
kubectl -n media get job thumbnails                   # COMPLETIONS 5/5

Example · Find out why a Job failed

kubectl get jobs shows report as Failed with COMPLETIONS 0/1.

kubectl describe job report | sed -n '/Conditions/,$p'
# Type    Status  Reason
# Failed  True    BackoffLimitExceeded
# Events:
#   Normal   SuccessfulCreate      pod: report-8bq2d ... report-x4wlm
#   Warning  BackoffLimitExceeded  Job has reached the specified backoff limit

kubectl get pods -l job-name=report                  # several Pods in Error
kubectl logs report-x4wlm                            # the application's own error message

The reason tells you where to look. BackoffLimitExceeded: the Pods ran and failed, so read their logs and exit codes. DeadlineExceeded: the Job was too slow, or its Pods never started (check Pending Pods and their events). A Pod stuck in ImagePullBackOff never fails, so it does not use up retries; it only runs into the deadline.

Example · Clean up automatically

Add the TTL to an existing Job, which is allowed even after it finished:

kubectl patch job db-migrate --type merge -p '{"spec":{"ttlSecondsAfterFinished":60}}'
kubectl get job db-migrate        # gone about a minute after it finished

Tricks

Common mistakes

  • Leaving restartPolicy out of a hand-written Job. The Pod default is Always, which a Job rejects.
  • Putting completions or backoffLimit under template.spec. They belong to the Job's own spec.
  • Trying to edit the image of a Job. The template is immutable. Delete and recreate, or kubectl replace --force.
  • Re-applying a Job manifest to run the task again. An unchanged, finished Job is not run again. Delete it first, or give the new one another name.
  • Expecting a Job to be deleted when it finishes. It stays until ttlSecondsAfterFinished or a manual delete.
  • Reading only kubectl get pods. With OnFailure, the failed attempts are restarts of one Pod, and after the Job fails that Pod may be gone. kubectl describe job keeps the reason.
  • Confusing the two activeDeadlineSeconds. In the Job spec it limits the whole Job; in the Pod template it limits each Pod.

Recap

  • A Job runs Pods until completions of them have succeeded (default 1), at most parallelism at a time, and then stops. Its template needs restartPolicy: Never or OnFailure.
  • Failed Pods are retried with a growing delay (10 s, 20 s, 40 s, up to 6 min). The Job fails after backoffLimit failures (default 6), after activeDeadlineSeconds, or on a FailJob rule of a podFailurePolicy.
  • completionMode: Indexed gives every Pod a number in JOB_COMPLETION_INDEX; the Job completes when every index has succeeded.
  • Finished Jobs stay until ttlSecondsAfterFinished or kubectl delete job, which also deletes their Pods. The Pod template is immutable.
  • In the exam: kubectl create job NAME --image=IMG -- CMD, add fields to spec from a dry run, read kubectl describe job for the reason, and kubectl logs job/NAME for the output.

Official docs

Quiz: check what you learned

6 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Run a batch task as a parallel Job with retry and clean-up rules, and repair a Job that ran out of retries.

    Build · Level 2 · standard · target 20 min

  • A log shipper keeps a Job running forever. Turn it into a native sidecar so the Job completes and no line is lost.

    Fix · Level 2 · standard · target 15 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.