Kubernetes Job and CronJob
Explore Kubernetes Jobs and CronJobs for batch processing, completions, parallelism, restart policies, scheduling syntax, and interview questions.
While Deployments and DaemonSets manage long-running services that should never terminate, Kubernetes Job and CronJob controllers manage batch processes and scheduled tasks that run to completion. A Job creates one or more Pods, tracks their execution, and ensures that a specified number of Pods exit successfully with code 0. A CronJob adds time-based execution on top of Jobs, enabling automated periodic tasks such as backups, report generation, and data synchronization.
Core Concepts and Lifecycle
When a Job starts, it spawns Pods according to its parallelism and completion configuration. If a container crashes, the Job controller handles restarts according to the configured restartPolicy and backoffLimit. Once the required successful completions are reached, the Job marks itself as complete and stops creating Pods.
| Resource / Setting | Purpose | Key Values / Examples |
|---|---|---|
Job |
One-off batch execution to completion | completions, parallelism, backoffLimit |
CronJob |
Periodic, schedule-driven batch execution | schedule: "0 2 * * *", concurrencyPolicy |
restartPolicy |
Container restart behavior in Job Pods | OnFailure (restart in-place) or Never (spawn new Pod) |
concurrencyPolicy |
Handles concurrent runs of the same CronJob | Allow (default), Forbid, Replace |
ttlSecondsAfterFinished |
Auto-deletes finished Jobs and Pods from etcd | Integer in seconds (e.g., 300) |
Concurrency Policies in CronJobs
When a scheduled execution time arrives while a previous execution is still running, concurrencyPolicy determines the behavior:
Allow: Runs concurrent Job instances simultaneously without restriction.Forbid: Skips the new execution if the previous Job has not finished yet.Replace: Cancels the currently running Job and starts a new one in its place.
Manifests
1. Production Job Manifest
The following manifest defines a database migration Job configured with parallel workers, exponential retry backoff, and automatic TTL cleanup:
apiVersion: batch/v1
kind: Job
metadata:
name: data-indexer
namespace: batch-jobs
spec:
completions: 4
parallelism: 2
backoffLimit: 3
activeDeadlineSeconds: 600
ttlSecondsAfterFinished: 300
template:
metadata:
labels:
app: data-indexer
spec:
restartPolicy: OnFailure
containers:
- name: indexer
image: busybox:1.36
command: ["sh", "-c", "echo 'Indexing data batch...' && sleep 10 && exit 0"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 250m
memory: 256Mi
2. Production CronJob Manifest
The following manifest runs a nightly database backup at 02:00 UTC with a strict Forbid concurrency policy:
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-db-backup
namespace: batch-jobs
spec:
schedule: "0 2 * * *"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 200
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 1800
template:
spec:
restartPolicy: OnFailure
containers:
- name: db-backup
image: postgres:16-alpine
command: ["sh", "-c", "pg_dumpall -h db.internal -U postgres > /tmp/backup.sql && echo Backup complete"]
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
Managing Jobs and CronJobs with kubectl
# Check existing Jobs and their completion status
kubectl get jobs -n batch-jobs
# NAME COMPLETIONS DURATION AGE
# data-indexer 4/4 25s 2m
# Stream logs from a Job Pod
kubectl logs -f job/data-indexer -n batch-jobs
# Manually trigger a Job from an existing CronJob definition
kubectl create job --from=cronjob/nightly-db-backup manual-backup-01 -n batch-jobs
# Suspend a CronJob from running future schedules
kubectl patch cronjob nightly-db-backup -n batch-jobs -p '{"spec":{"suspend":true}}'
Common Mistakes
- Using restartPolicy: Always: A Job template cannot use
restartPolicy: Always. Kubernetes rejects the manifest; onlyOnFailureorNeverare valid. - Omitting concurrencyPolicy on heavy CronJobs: Leaving
concurrencyPolicy: Allowon long-running jobs can lead to overlapping runs that saturate database connections or CPU limits. - Missing ttlSecondsAfterFinished: Without a TTL controller setting or manual cleanup, finished Job Pods linger forever in
Completedstatus, consuming IP ranges and cluttering cluster state. - No activeDeadlineSeconds: If a batch job deadlocks on a remote lock or hanging network socket, it runs forever without terminating or triggering retries.
Best Practices
- Always configure
ttlSecondsAfterFinishedto prevent accumulation of completed Pods in etcd. - Set
activeDeadlineSecondson critical Jobs to enforce a hard maximum execution time. - Use
concurrencyPolicy: Forbidfor batch operations that modify shared state or mutate database tables. - Adjust
successfulJobsHistoryLimit(default 3) andfailedJobsHistoryLimit(default 1) to conserve cluster resource metadata.
Interview Questions
1. What is the difference between a Job and a Deployment in Kubernetes?
A Deployment manages continuous, long-running services (like HTTP servers) where Pods should never exit; if a container stops, the Deployment controller restarts or recreates it. A Job manages short-lived, run-to-completion batch tasks (like batch processing or schema migrations); once the Pod completes successfully with exit code 0, the Job finishes and does not restart it.
2. How do completions and parallelism interact in a Job?
completions defines how many Pods must terminate with exit code 0 before the Job is considered complete. parallelism defines how many Pods can run concurrently at any given point in time. For example, with completions: 6 and parallelism: 2, Kubernetes runs 2 Pods at a time until 6 successful completions have accumulated.
3. What is the difference between restartPolicy: OnFailure and restartPolicy: Never in a Job?
With restartPolicy: OnFailure, if a container fails, the kubelet restarts the container inside the same Pod instance on the same node. With restartPolicy: Never, the kubelet does not restart failed containers; instead, the Job controller creates an entirely new Pod on an available node and increments the failure count towards backoffLimit.
4. What are the three CronJob concurrency policies?
The three policies are Allow (runs new Jobs concurrently even if an older Job is still running), Forbid (skips the scheduled execution if the previous Job has not finished), and Replace (aborts the currently running Job and starts the new instance immediately).
5. What does startingDeadlineSeconds do in a CronJob?
startingDeadlineSeconds sets the maximum window (in seconds) for a CronJob to start if it missed its scheduled execution time due to controller downtime or resource shortages. If the controller misses the schedule by more than this deadline, Kubernetes logs the missed run and waits for the next scheduled occurrence instead of running stale executions.
6. How do you trigger an immediate one-off run from a CronJob?
You can instantiate a Job directly from a CronJob specification using the command kubectl create job --from=cronjob/<cronjob-name> <custom-job-name>.
Summary
- Jobs manage run-to-completion tasks, whereas CronJobs manage time-scheduled Jobs.
restartPolicyin Job templates must beOnFailureorNever, notAlways.- Use
concurrencyPolicy: Forbidto prevent simultaneous runs from overloading systems. - Set
ttlSecondsAfterFinishedandactiveDeadlineSecondsfor automated lifecycle and timeout safety.
Continue Learning
Previous: DaemonSet | Next: Resource Limits
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.