Skip to main content

Running Batch Workloads with Jobs and CronJobs

Run one-off and scheduled batch work on Kubernetes with Jobs and CronJobs, covering retries, parallelism, concurrency policy and cleanup.

52 Terms

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, backoffLimit and activeDeadlineSeconds
  • 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.

flowchart TD CJ["CronJob
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
Bash
kubectl create namespace batch-lab
YAML
apiVersion: batch/v1
kind: Job
metadata:
name: hello-job
namespace: batch-lab
spec:
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"]
Bash
kubectl apply -f hello-job.yaml
kubectl get jobs -n batch-lab -w
# COMPLETIONS goes from 0/1 to 1/1
kubectl logs job/hello-job -n batch-lab
kubectl describe job hello-job -n batch-lab

The 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:

YAML
# failing-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: failing-job
namespace: batch-lab
spec:
backoffLimit: 2
activeDeadlineSeconds: 300
template:
spec:
restartPolicy: Never
containers:
- name: fail
image: busybox:1.36
command: ["sh", "-c", "echo attempting; exit 1"]
Bash
kubectl apply -f failing-job.yaml
kubectl 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 prefix
kubectl logs -n batch-lab -l job-name=failing-job --prefix

The 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:

YAML
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:

YAML
# indexed-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: image-resize
namespace: batch-lab
spec:
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"]
Bash
kubectl apply -f indexed-job.yaml
kubectl get pods -n batch-lab -l job-name=image-resize -w
kubectl logs -n batch-lab -l job-name=image-resize --prefix
# Expected: one pod per shard 0 to 5, no more than 3 running at once

For 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:

YAML
# report-cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-report
namespace: batch-lab
spec:
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"]
Bash
kubectl apply -f report-cronjob.yaml
kubectl get cronjob nightly-report -n batch-lab
kubectl get jobs -n batch-lab -w

The 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:

Bash
RUN=manual-run-$(date +%s)
kubectl create job --from=cronjob/nightly-report $RUN -n batch-lab
kubectl logs job/$RUN -n batch-lab
kubectl patch cronjob nightly-report -n batch-lab --type=merge --patch-file suspend.yaml
YAML
# suspend.yaml
spec:
suspend: true
Step 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:

Bash
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 5
done
kubectl apply -f deployment.yaml -n production

Many 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
Bash
kubectl delete namespace batch-lab

Production Best Practices & Common Pitfalls

Common Mistake

Leaving 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.

Tip

Set successfulJobsHistoryLimit: 3 and failedJobsHistoryLimit: 5 on every CronJob. The default of one failed Job means you lose the first failure's logs the moment a second failure occurs.

Remember

Set ttlSecondsAfterFinished on 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. activeDeadlineSeconds stops 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_failed metric from kube-state-metrics.
  • Use the cleanup commands for strays. kubectl delete jobs --field-selector status.successful=1 -n NS removes 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

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Workload Management

All 6 Topics

Frequently Asked Questions

Is Running Batch Workloads with Jobs and CronJobs free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Running Batch Workloads with Jobs and CronJobs topic cover?

Run one-off and scheduled batch work on Kubernetes with Jobs and CronJobs, covering retries, parallelism, concurrency policy and cleanup.

Found a mistake, an outdated step or a broken link?