Jobs & CronJobs
Be able to explain it and pass its lab once. Phase 5 of the Learning Path.
Docs: Jobs Β· CronJob Β· Indexed Jobs
Overviewβ
A Deployment keeps Pods running forever. A Job runs Pods until a set number of them succeed, then stops. A CronJob creates a Job on a schedule. They are the same reconcile loop as every other controller (β Architecture), except "done" is a reachable state. Use a Job for migrations, batch processing and one-off tasks. Use a CronJob for anything that should happen every night, hour or minute. The interview questions almost always concern failure: retries, overlapping runs and runs that never happened.
Key conceptsβ
Job fieldsβ
| Field | Default | What it controls |
|---|---|---|
completions | 1 | How many Pods must succeed |
parallelism | 1 | How many Pods run at once |
backoffLimit | 6 | Retries before the Job is marked Failed. Delays grow 10s, 20s, 40s⦠up to 6 min. |
activeDeadlineSeconds | none | Hard wall-clock limit for the whole Job. Beats backoffLimit. |
ttlSecondsAfterFinished | none | Delete the Job and its Pods this long after it finishes |
completionMode: Indexed | NonIndexed | Each Pod gets JOB_COMPLETION_INDEX (0β¦n-1) to pick its slice of work |
template.spec.restartPolicy | (required) | OnFailure or Never. Always is rejected. |
restartPolicy inside a Jobβ
| Value | On failure | Result |
|---|---|---|
OnFailure | Container restarts in the same Pod | Fewer Pods, but the failed container's logs are replaced |
Never | A new Pod is created | Failed Pods stay for kubectl logs. Use while debugging. |
Always | (rejected by the API) | Validation error |
CronJob fieldsβ
| Field | Default | What it controls |
|---|---|---|
schedule | (required) | Cron syntax: minute hour day-of-month month day-of-week |
timeZone | controller's zone, usually UTC | IANA name such as Asia/Singapore |
concurrencyPolicy | Allow | What happens when the previous run is still going (table below) |
startingDeadlineSeconds | none | If a run is missed by more than this, skip it |
successfulJobsHistoryLimit / failedJobsHistoryLimit | 3 / 1 | How many finished Jobs to keep |
suspend | false | Pause scheduling without deleting the CronJob |
concurrencyPolicyβ
| Value | Previous run still active | Result |
|---|---|---|
Allow | Start another one | Two retraining runs writing the same files. Usually a bug. |
Forbid | Skip this run | Safe for jobs that must not overlap. A slow run means missed runs. |
Replace | Kill the old run, start the new one | Latest data wins. A run that always overruns never finishes. |
kubectl essentialsβ
Create imperatively:
kubectl create job hello --image=busybox:1.36 -- sh -c 'echo hello; sleep 5'
kubectl create cronjob report --image=busybox:1.36 --schedule="*/5 * * * *" -- date
kubectl create job report-manual --from=cronjob/report # run a CronJob now
kubectl create job hello --image=busybox:1.36 --dry-run=client -o yaml -- echo hi > job.yaml
Inspect and control:
kubectl get jobs,cronjobs
kubectl logs job/hello # logs of one of the Job's Pods
kubectl get pods -l job-name=hello # every Pod the Job created
kubectl wait --for=condition=complete job/hello --timeout=120s
kubectl patch cronjob report -p '{"spec":{"suspend":true}}'
A parallel Job with bounded retries and cleanup:
apiVersion: batch/v1
kind: Job
metadata:
name: process
spec:
completions: 5
parallelism: 2
backoffLimit: 3
activeDeadlineSeconds: 600
ttlSecondsAfterFinished: 3600
completionMode: Indexed
template:
spec:
restartPolicy: Never
containers:
- name: worker
image: busybox:1.36
command: ["sh", "-c", "echo processing shard $JOB_COMPLETION_INDEX; sleep 5"]
A nightly CronJob that must never overlap:
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-report
spec:
schedule: "0 2 * * *"
timeZone: Asia/Singapore
concurrencyPolicy: Forbid
startingDeadlineSeconds: 1800
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 7200
template:
spec:
restartPolicy: OnFailure
containers:
- name: report
image: busybox:1.36
command: ["sh", "-c", "echo building report; sleep 30"]
π§ͺ Labβ
Requires: Standard lab setup Β· Generate, edit, apply Β· How the tiers work.
Watch concurrencyPolicy: Forbid skip a run.
Goal
- In namespace
lab5-1, create a CronJobslowthat runs every minute, sleeps 90 seconds, and usesconcurrencyPolicy: Forbid. - Watch Jobs for 4 minutes. Explain why there are fewer Jobs than minutes.
- Trigger a manual run from the CronJob and confirm it runs even while a scheduled one is active.
- Suspend the CronJob.
Verify
kubectl -n lab5-1 get cronjob slow -o jsonpath='{.spec.concurrencyPolicy} {.spec.suspend}{"\n"}' # Forbid true
kubectl -n lab5-1 get jobs
π‘ Hints
kubectl create cronjob -h. The generator can't setconcurrencyPolicy: generate, edit, apply.kubectl get jobs -w. Compare each run's length with the schedule interval.kubectl create job -hhas a--fromflag.suspendis a boolean in the CronJob's spec.kubectl patchsets one field.
π’ Guided
-
Create the lab namespace.
kubectl create namespace lab5-1 -
Generate a CronJob manifest that runs every minute and sleeps 90s.
kubectl -n lab5-1 create cronjob slow --image=busybox:1.36 --schedule="* * * * *" \--dry-run=client -o yaml -- sleep 90 > slow.yaml -
Edit
slow.yaml: addconcurrencyPolicy: Forbidunderspec:. -
Create the CronJob from the edited file.
kubectl -n lab5-1 apply -f slow.yaml -
Watch Jobs appear.
kubectl -n lab5-1 get jobs -wNAME STATUS COMPLETIONS DURATION AGEslow-29841788 Complete 1/1 93s 3m20sslow-29841789 Complete 1/1 93s 107sslow-29841791 Running 0/1 14s 14sThree Jobs in over four minutes, never two at once. Forbid doesn't start a tick that finds a run active, but with no
startingDeadlineSecondsthe missed tick isn't lost either: the controller starts it late, as soon as the previous run finishes. So runs go back to back (...89started when...88ended), and ticks that pile up collapse into one (...90never ran). SetstartingDeadlineSecondsif a late run is worse than no run. -
Start a Job from the CronJob's template right now.
kubectl -n lab5-1 create job slow-manual --from=cronjob/slowManual Jobs bypass concurrencyPolicy. That rule is the CronJob controller's, not the Job's.
-
Pause the schedule without deleting the CronJob.
kubectl -n lab5-1 patch cronjob slow -p '{"spec":{"suspend":true}}' -
Run the β Check below, then delete everything the lab created.
kubectl delete namespace lab5-1
β Check
t() { [ "$2" = "$3" ] && echo "PASS $1" || echo "FAIL $1: got '$2', want '$3'"; }
t "concurrencyPolicy Forbid" "$(kubectl -n lab5-1 get cronjob slow -o jsonpath='{.spec.concurrencyPolicy}')" "Forbid"
t "suspended" "$(kubectl -n lab5-1 get cronjob slow -o jsonpath='{.spec.suspend}')" "true"
t "manual run created" "$(kubectl -n lab5-1 get job slow-manual -o jsonpath='{.metadata.name}')" "slow-manual"
t "never 2 scheduled at once" "$(kubectl -n lab5-1 get jobs -o jsonpath='{range .items[*]}{.metadata.name} {.status.active}{"\n"}{end}' | grep -v manual | grep -c ' 1$' | awk '{print ($1<=1)?"yes":"no"}')" "yes"
Gotchasβ
- Time zone. Without
timeZone,0 2 * * *means 02:00 in the controller-manager's zone, usually UTC. - Jobs must be idempotent. The controller can occasionally create two Jobs for one schedule, or none. Design for it.
- Finished Jobs pile up. Standalone Jobs stay forever unless you set
ttlSecondsAfterFinished. OnFailurerestarts count too. Container restarts inside a Pod burnbackoffLimitjust like failed Pods. SetactiveDeadlineSecondsas the real cap.- Too many missed runs. If more than 100 schedules are missed (for example, after a long suspend without
startingDeadlineSeconds), the CronJob stops scheduling and logs an error. - Editing a CronJob doesn't touch running Jobs. Only the next Job uses the new template.
Scenario questionsβ
Q1 β A Job has created a string of failed Pods and stopped. What happened and what do you check?
Model answer
- Clarify: did it ever succeed? Is this a new image or new input data?
- Observe:
kubectl describe jobshowsBackoffLimitExceeded.kubectl logson the newest failed Pod shows the error.restartPolicy: Neverkept each failed Pod, one per attempt. - Hypothesise: the task fails deterministically: a bad argument, a missing Secret, or bad data.
- Fix: fix the cause, delete the Job, re-create it. A failed Job does not retry on its own.
- Prevent: lower
backoffLimitfor deterministic failures and alert on Job failure. UsepodFailurePolicyto fail fast on exit codes that retries can't fix.
Q2 β β The nightly job sometimes runs twice at once and corrupts its output. How do you stop that?
Model answer
- Clarify: how long does a run take compared to the schedule interval? Does it ever run long?
- Observe:
kubectl get jobsshows two active Jobs with overlapping start times.concurrencyPolicyisAllow, the default. - Hypothesise: a slow night pushed a run past the next schedule, and
Allowstarted a second one. - Fix: set
concurrencyPolicy: ForbidandactiveDeadlineSecondsso a hung run can't block every later one. - Prevent: make the job idempotent anyway (write to a temp path, then rename), because the controller doesn't strictly guarantee one run per schedule. The trade-off:
Forbidmeans a slow run skips the next one, so alert on missed runs.
Q3 β β The CronJob didn't run last night. Where do you look?
Model answer
- Clarify: didn't run at all, or ran and failed?
- Observe:
kubectl get cronjobforSUSPENDandLAST SCHEDULE.kubectl describe cronjobfor events such as missed schedules.kubectl get jobsfor a failed Job. - Hypothesise: suspended; the previous run still active under
Forbid; the start was later thanstartingDeadlineSecondsbecause the control plane was down; or the schedule is in UTC while you expected local time. - Fix: resume it, set
timeZone, or trigger a catch-up withkubectl create job --from=cronjob/<name>. - Prevent: alert when the last successful run is older than the interval, a "dead man's switch".
Q4 β β β You must process 1,000 files as fast as possible without a message queue. Design it.
Model answer
- Clarify: are files independent? How long does one take? What limits parallelism: cluster capacity or a downstream API?
- Observe: independent files and a fixed list make static partitioning possible.
- Hypothesise: an Indexed Job with
completions: 100andparallelism: 20. Each Pod readsJOB_COMPLETION_INDEXand processes filesindex*10toindex*10+9. - Fix: set
backoffLimitPerIndexso one bad shard retries alone and doesn't fail the whole Job. Sizeparallelismto what the downstream can take, not the cluster. - Prevent: trade-off vs a queue: indexed Jobs are simple and need no infrastructure, but work is split up front. If items vary wildly in cost, a work queue balances load better.
Summaryβ
- Jobs run to completion; Deployments run forever. Pick by whether "done" exists.
backoffLimitretries,activeDeadlineSecondscaps. Set both.concurrencyPolicy: Forbidstops overlapping runs. The cost is skipped runs when one is slow.- Always set
timeZoneandttlSecondsAfterFinished. UTC surprises and piles of finished Jobs are the two classic messes. - Make every Job idempotent. Retries and the occasional double run are part of the contract.
Next in path β Storage