Overview and What You Will Learn
A Kubernetes Job runs a pod until the task succeeds and then stops, and a CronJob creates a Job on a schedule. A Deployment is the wrong tool for finite work, because it restarts a pod that exits even when the task was finished or partly done. In this lab you will run a successful Job, a failing Job, an indexed parallel Job and a CronJob, and trigger a CronJob by hand.
- Choosing between a Deployment and a Job
- Setting
restartPolicy,backoffLimitandactiveDeadlineSeconds - Running parallel work with indexed Jobs
- Scheduling with CronJobs, time zones and
concurrencyPolicy - Triggering and cleaning up Jobs
- Running a database migration safely before a deploy
Why This Matters in Production
Batch tasks need different guarantees than servers: they must finish, retry in a controlled way, and not run twice at once. Imagine a team at a company like Razorpay that runs a schema migration as a Deployment. If the migration pod exits after a partial run, the controller restarts it automatically, and a half-finished migration runs again. A Job runs the task to completion, limits retries, and leaves the pod and its logs for inspection.
Core Principles
A Job guarantees at-least-once execution, which means a task can occasionally run more than once, so batch code must be idempotent. A CronJob does not run pods itself. At each scheduled time it creates a Job, and the Job creates the pod.
schedule 0 2 * * *"]:::tool -->|creates at each run| J[Job]:::tool J -->|creates| P[Pod]:::soft P --> R([Runs to completion]):::ok classDef tool fill:#326CE5,color:#FFFFFF classDef soft fill:#DBEAFE,color:#1E293B classDef ok fill:#10B981,color:#FFFFFF
| Deployment | Job | |
|---|---|---|
| Lifetime | Runs forever | Runs to completion |
| On exit | Restarts the pod | Counts a success or retries on failure |
| Typical use | Web servers and APIs | Migrations, reports, data pipelines |
The restartPolicy of a Job's pod must be Never or OnFailure, never Always:
| Policy | Behavior | Use when |
|---|---|---|
Never |
Each failure creates a new pod | You want a clean pod per attempt, as with migrations |
OnFailure |
The same pod restarts its container | A restart in place is safe |
Detailed Step-by-Step Practical Lab
Step 1 - Run a Simple Job
kubectl create namespace batch-labapiVersion: batch/v1kind: Jobmetadata: name: hello-job namespace: batch-labspec: backoffLimit: 3 ttlSecondsAfterFinished: 600 template: spec: restartPolicy: Never containers: - name: hello image: busybox:1.36 command: ["sh", "-c", "echo processing report; sleep 5; echo done"]kubectl apply -f hello-job.yamlkubectl get jobs -n batch-lab -w# COMPLETIONS goes from 0/1 to 1/1 kubectl logs job/hello-job -n batch-labkubectl describe job hello-job -n batch-labThe pod stays in Completed state so you can read its logs, and ttlSecondsAfterFinished deletes the Job and its pods 10 minutes later.
Step 2 - Watch a Job Fail and Retry
backoffLimit is the number of retries after the first attempt, so backoffLimit: 2 allows three attempts in total. Kubernetes waits longer between retries, starting at 10 seconds and doubling:
# failing-job.yamlapiVersion: batch/v1kind: Jobmetadata: name: failing-job namespace: batch-labspec: backoffLimit: 2 activeDeadlineSeconds: 300 template: spec: restartPolicy: Never containers: - name: fail image: busybox:1.36 command: ["sh", "-c", "echo attempting; exit 1"]kubectl apply -f failing-job.yamlkubectl get pods -n batch-lab -l job-name=failing-job -w kubectl describe job failing-job -n batch-lab# Events show: Warning BackoffLimitExceeded Job has reached the specified backoff limit # Logs from every attempt, with the pod name as a prefixkubectl logs -n batch-lab -l job-name=failing-job --prefixThe activeDeadlineSeconds field sets a hard time limit for the whole Job and takes priority over retries. To stop retrying when a failure is permanent, such as bad input, use a pod failure policy that fails the Job on a specific exit code. It requires restartPolicy: Never:
spec: backoffLimit: 6 podFailurePolicy: rules: - action: FailJob onExitCodes: containerName: migration operator: In values: [42]Step 3 - Run Parallel Work with an Indexed Job
Setting completions and parallelism alone only starts that many identical pods, so every pod does the same work. An indexed Job gives each pod a unique index in the JOB_COMPLETION_INDEX environment variable, which lets each pod process its own shard. Kubernetes starts a new pod as soon as one finishes, up to the parallelism limit:
# indexed-job.yamlapiVersion: batch/v1kind: Jobmetadata: name: image-resize namespace: batch-labspec: completionMode: Indexed completions: 6 parallelism: 3 backoffLimit: 6 template: spec: restartPolicy: Never containers: - name: worker image: busybox:1.36 command: ["sh", "-c", "echo processing shard $JOB_COMPLETION_INDEX; sleep 5"]kubectl apply -f indexed-job.yamlkubectl get pods -n batch-lab -l job-name=image-resize -wkubectl logs -n batch-lab -l job-name=image-resize --prefix# Expected: one pod per shard 0 to 5, no more than 3 running at onceFor a work queue, such as messages in a queue, set parallelism and leave completions unset, and have each worker pull from the queue until it is empty.
Step 4 - Schedule a CronJob
Every minute is only for the lab. The schedule is read in the timeZone you set, available from Kubernetes 1.27, and otherwise in the controller manager's time zone, which is usually UTC:
# report-cronjob.yamlapiVersion: batch/v1kind: CronJobmetadata: name: nightly-report namespace: batch-labspec: schedule: "*/1 * * * *" timeZone: "Asia/Kolkata" concurrencyPolicy: Forbid startingDeadlineSeconds: 300 successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 5 jobTemplate: spec: backoffLimit: 2 ttlSecondsAfterFinished: 3600 template: spec: restartPolicy: OnFailure containers: - name: report-generator image: busybox:1.36 command: ["sh", "-c", "echo generating report for $(date); sleep 90"]kubectl apply -f report-cronjob.yamlkubectl get cronjob nightly-report -n batch-labkubectl get jobs -n batch-lab -wThe container sleeps for 90 seconds, longer than the one-minute schedule, so the next run is due while the last is still running. With concurrencyPolicy: Forbid, Kubernetes skips the new run instead of overlapping. The concurrencyPolicy field takes three values:
| Policy | Behavior | Use when |
|---|---|---|
Allow (default) |
Runs overlap freely | The task is idempotent and overlap is harmless |
Forbid |
Skips the new run while the last is still running | Reports and reconciliations where overlap would duplicate data |
Replace |
Stops the running Job and starts the new one | Freshness matters more than finishing |
The schedule has five fields: minute, hour, day of month, month and day of week (0 to 6, Sunday as 0). Day of month and day of week combine with OR when both are restricted, as in standard cron.
| Schedule | Meaning |
|---|---|
0 * * * * |
Every hour on the hour |
*/15 * * * * |
Every 15 minutes |
0 2 * * * |
Every day at 02:00 |
0 2 * * 1 |
Every Monday at 02:00 |
0 0 1 * * |
First day of each month at midnight |
0 9-18 * * 1-5 |
Hourly from 09:00 to 18:00 on weekdays |
Use the timeZone field rather than putting TZ= or CRON_TZ= in the schedule, which newer Kubernetes versions reject.
Step 5 - Trigger a CronJob by Hand and Pause It
A CronJob cannot be run directly, but you can create a Job from its template. You can also pause the schedule without deleting anything:
RUN=manual-run-$(date +%s)kubectl create job --from=cronjob/nightly-report $RUN -n batch-labkubectl logs job/$RUN -n batch-lab kubectl patch cronjob nightly-report -n batch-lab --type=merge --patch-file suspend.yaml# suspend.yamlspec: suspend: trueStep 6 - Run a Migration Before a Deploy
Run the migration as a Job, wait for it to finish or fail, and deploy only on success. Waiting only for complete would hang until the timeout if the Job fails, so poll for either result:
kubectl apply -f db-migration-job.yaml -n production for i in $(seq 1 60); do status=$(kubectl get job db-migration-v2 -n production \ -o jsonpath='{.status.conditions[?(@.status=="True")].type}') [ "$status" = "Complete" ] && break [ "$status" = "Failed" ] && { echo "Migration failed"; exit 1; } sleep 5done kubectl apply -f deployment.yaml -n productionMany teams do this with a pre-deploy hook in Helm or Argo CD instead. Either way, write migrations so that running one twice is safe, and rely on the migration tool's own locking so two runs cannot overlap.
Step 7 - Clean Up
kubectl delete namespace batch-labProduction Best Practices & Common Pitfalls
Common MistakeLeaving
concurrencyPolicy: Allow, the default, on a report or reconciliation job that sometimes runs long. The next run starts while the last is still going, and the overlap can duplicate rows and corrupt results. Set the policy explicitly on every CronJob.
TipSet
successfulJobsHistoryLimit: 3andfailedJobsHistoryLimit: 5on every CronJob. The default of one failed Job means you lose the first failure's logs the moment a second failure occurs.
RememberSet
ttlSecondsAfterFinishedon Jobs created by CI/CD pipelines. Without it, completed Jobs and pods accumulate in the namespace and in etcd, so give them a lifetime of one to 24 hours.
- Design for at-least-once. A Job can run a task twice after a node failure or a retry, so make the work idempotent.
- Set resource requests and limits. Batch pods without requests can be packed onto busy nodes or starve other workloads.
- Be aware of missed runs. A CronJob skips a run that misses its
startingDeadlineSeconds, and if it misses more than 100 schedules in a row it stops starting Jobs until you fix it. - Set a deadline.
activeDeadlineSecondsstops a hung Job from running forever and holding resources. - Alert on failed Jobs. Kubernetes will not tell you a nightly Job has been failing, so alert on the
kube_job_failedmetric from kube-state-metrics. - Use the cleanup commands for strays.
kubectl delete jobs --field-selector status.successful=1 -n NSremoves completed Jobs, and a TTL prevents the build-up in the first place.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl get jobs -n NS -w |
Watch Job progress |
kubectl logs job/NAME -n NS |
Read a Job's pod logs |
kubectl logs -n NS -l job-name=NAME --prefix |
Read logs from all of a Job's pods |
kubectl describe job NAME -n NS |
Show events, retries and failures |
kubectl create job --from=cronjob/NAME RUN -n NS |
Run a CronJob's template now |
kubectl get cronjob -n NS |
Show schedules, last run and suspend state |
kubectl delete jobs --field-selector status.successful=1 -n NS |
Delete completed Jobs |