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
Official competencies this lesson covers
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 task | Examples |
|---|---|
| One-off maintenance | A database schema migration, re-indexing a search engine, rotating a key |
| Batch processing | Resizing 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.
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:
| Field | Default | Meaning |
|---|---|---|
completions | 1 | How many Pods must succeed for the Job to be complete |
parallelism | 1 | How many Pods may run at the same time |
backoffLimit | 6 | How many failed Pods (or container restarts with OnFailure) before the Job fails |
activeDeadlineSeconds | none | The longest the Job may run, counted from its start; then it fails |
ttlSecondsAfterFinished | none | Seconds after the Job finishes (Complete or Failed) before it is deleted with its Pods |
completionMode | NonIndexed | Indexed gives each Pod a number from 0 to completions - 1 |
suspend | false | true stops creating Pods and deletes running ones; false resumes |
podFailurePolicy | none | Rules 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:
| Column | Meaning |
|---|---|
STATUS | Running, Complete, Failed or Suspended |
COMPLETIONS | Successful Pods out of completions, for example 3/5 |
DURATION | From 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:
- Count Pods: active, succeeded, failed
- Succeeded = completions? Mark Complete, stop
- Failed > backoffLimit or deadline passed? Mark Failed, stop Pods
- Active < parallelism and successes still missing? Create Pods
- Write the counts to status
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:
restartPolicy | When the container fails | What you see | Counted against backoffLimit |
|---|---|---|---|
Never | The Pod fails; the Job controller creates a new Pod | Several Pods, Error on the failed ones | Each failed Pod |
OnFailure | The kubelet restarts the container in the same Pod | One Pod with a growing RESTARTS count, CrashLoopBackOff | Each 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.
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
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:
| Shape | completions | parallelism | Behaviour |
|---|---|---|---|
| One task | 1 (default) | 1 (default) | One Pod at a time until one succeeds |
| Fixed number of tasks | N | 1 to N | Runs up to parallelism Pods; complete after N successes |
| Work queue | unset | N | Runs 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"]
| Action | Effect |
|---|---|
FailJob | The Job fails at once with reason PodFailurePolicy; running Pods are stopped |
Ignore | The failure is not counted against backoffLimit; a replacement Pod is created |
Count | The default behaviour: counts as one failure |
FailIndex | Indexed 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:
| Way | How |
|---|---|
| Automatic, per Job | ttlSecondsAfterFinished: 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 Jobs | A CronJob keeps only its last few Jobs (next lesson) |
| By hand | kubectl 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 want | Use |
|---|---|
| A task that runs once until it succeeds | Job |
| The same task on a schedule | CronJob (next lesson), which creates Jobs |
| A process that runs all the time | Deployment |
| A task once on every node | A DaemonSet, removed afterwards; a Job cannot target "each node" |
| Setup before the main container starts, inside one Pod | An 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
restartPolicyout of a hand-written Job. The Pod default isAlways, which a Job rejects. - Putting
completionsorbackoffLimitundertemplate.spec. They belong to the Job's ownspec. - 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
ttlSecondsAfterFinishedor a manual delete. - Reading only
kubectl get pods. WithOnFailure, the failed attempts are restarts of one Pod, and after the Job fails that Pod may be gone.kubectl describe jobkeeps 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
completionsof them have succeeded (default 1), at mostparallelismat a time, and then stops. Its template needsrestartPolicy: NeverorOnFailure. - Failed Pods are retried with a growing delay (10 s, 20 s, 40 s, up to 6 min). The Job fails after
backoffLimitfailures (default 6), afteractiveDeadlineSeconds, or on aFailJobrule of apodFailurePolicy. completionMode: Indexedgives every Pod a number inJOB_COMPLETION_INDEX; the Job completes when every index has succeeded.- Finished Jobs stay until
ttlSecondsAfterFinishedorkubectl delete job, which also deletes their Pods. The Pod template is immutable. - In the exam:
kubectl create job NAME --image=IMG -- CMD, add fields tospecfrom a dry run, readkubectl describe jobfor the reason, andkubectl logs job/NAMEfor 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.