Most Kubernetes workloads never finish. A web server, an API, a database — these are long-running services that should stay up forever, and Kubernetes is built around keeping them alive. But a large share of real production work looks nothing like that. Database migrations run once and exit. Nightly reports generate a file and stop. A batch of ten thousand images needs processing, and when the last image is done, the work is over.
Kubernetes has dedicated workload types for work that finishes: Jobs and CronJobs. A Job runs one or more Pods until a defined amount of work completes successfully, then it stops. A CronJob creates Jobs on a schedule, the same way a cron entry on a Linux server runs a script at a set time. Together they cover one-off tasks, parallel batch processing, retries, scheduled maintenance and cleanup. If you are still getting oriented, start with our Kubernetes tutorial for beginners before going further.
This guide assumes you have kubectl configured against a cluster and a basic grasp of Pod specs. Every YAML example here is complete and ready to apply, and every behavior described is based on the current Kubernetes 1.37 release, known as Garhwal, with patch 1.37.3 released on 25 November 2026. The next minor release, 1.38, is planned for 16 December 2026 and is not yet released.
Why Deployments Cannot Do Finished Work
A Deployment exists to keep a desired number of Pods running. Its controller watches the actual state of the cluster, compares it to the desired state, and takes action whenever the two diverge. If a Pod crashes, the Deployment starts a replacement. This reconciliation loop is exactly what you want for a service, and exactly what you do not want for a task that is supposed to end.
Consider a database migration. You package the migration as a container image and run it as a Deployment with one replica. The migration runs, applies its changes, and exits with code zero — success. The Deployment controller sees a Pod that has terminated, decides the desired state is one running Pod, and immediately starts another one. The migration runs again, against an already-migrated database. Depending on how the migration is written, that second run might be harmless, might fail loudly, or might corrupt data.
The same problem appears with any finite task. A report generator that exits after writing its output gets restarted. A data import that completes gets re-run. A cleanup script that deletes old files gets scheduled again and again. Deployments have no concept of “done”. Their entire design assumes that a terminated Pod is a failure to be corrected, not a success to be celebrated.
There is a second, subtler problem. Deployments are built for rolling updates and scaling, and their controllers manage ReplicaSets, Pod templates and revision history. None of that machinery is useful for a one-off task, and it gets in the way when you want to answer simple questions: did this task succeed, how many times did it fail, and how long did it take? A Job answers those questions directly because completion is its whole purpose.
The practical rule is simple. If the process should run forever and serve traffic, use a Deployment. If it should run until it finishes and then stop, use a Job. If it should run on a schedule, use a CronJob. For the Deployment side of this picture, our Kubernetes Deployment YAML tutorial covers the full manifest in detail.
Writing Your First Job
A Job is a small manifest. At its core it is a Pod template wrapped in a Job spec, with two fields that control how the work is distributed: completions and parallelism. The simplest possible Job runs a single Pod once, waits for it to succeed, and marks the Job complete. Here is a Job that prints a message and exits, a useful smoke test for a new cluster:
apiVersion: batch/v1
kind: Job
metadata:
name: hello-job
spec:
template:
spec:
containers:
- name: hello
image: busybox:1.36
command: ["sh", "-c", "echo Hello from a Kubernetes Job; date"]
restartPolicy: Never
backoffLimit: 4
Apply it with kubectl and watch what happens:
kubectl apply -f hello-job.yaml
kubectl get jobs
kubectl get pods -l job-name=hello-job
kubectl logs job/hello-job
There are several things to notice in this manifest. The apiVersion is batch/v1, the stable API group for Jobs and CronJobs. The Pod template lives under spec.template.spec, exactly as it does in a Deployment, and it supports the same container fields: image, command, args, environment variables, resource requests and limits, volumes and probes. The restartPolicy field sits at the Pod level, not the Job level. A Job Pod must use restartPolicy: OnFailure or restartPolicy: Never. Setting restartPolicy: Always is invalid and the API server will reject the manifest, because a Job that restarts its Pods forever can never report completion. OnFailure restarts the container inside the same Pod when it exits with a nonzero code, while Never creates a fresh Pod for each retry attempt.
The backoffLimit field controls how many times the Job controller retries a failed Pod before declaring the whole Job failed. Its default is 6, which means a failing Job can consume a surprising amount of cluster time before it gives up, so setting it explicitly is good practice even when you are happy with the default, because it documents your intent. Between retries, the controller applies an exponential back-off delay, starting at ten seconds and doubling up to a cap of six minutes.
Checking the result of a Job is straightforward. kubectl get jobs shows a COMPLETIONS column, such as 1/1, and a DURATION column telling you how long the work took. kubectl logs job/hello-job fetches the logs of the Pod or Pods the Job created, which is convenient because you do not need to know the Pod name. When the Job completes, its Pods remain in the cluster in a Completed state until you delete them or a cleanup mechanism removes them. The official documentation for Jobs covers every field in the spec: Kubernetes Jobs documentation.
Completions and Parallelism: Batch Processing Patterns
A single Pod running once is the simplest Job, but the real power of the workload type appears when you need to process a large amount of work. The completions field tells the controller how many Pods must succeed before the Job is done, and the parallelism field tells it how many Pods may run at the same time. Together they describe a work queue with a defined size and a defined width.
Suppose you have five thousand images to resize. You could run one Pod that loops through all five thousand, but that takes hours and a single failure restarts everything. A better approach is a Job with completions set to 50 and parallelism set to 10. The controller creates up to ten Pods at a time, each claiming a chunk of the work, and starts another as each Pod finishes successfully, until fifty Pods have succeeded in total. The batch finishes roughly five times faster than a single Pod, and a failure in one Pod only re-runs that Pod’s chunk.
apiVersion: batch/v1
kind: Job
metadata:
name: image-resize-batch
spec:
completions: 50
parallelism: 10
template:
spec:
containers:
- name: resizer
image: registry.example.com/image-resizer:1.4.0
env:
- name: WORK_QUEUE_URL
value: "https://queue.internal.example.com/resize"
resources:
requests:
cpu: "500m"
memory: "512Mi"
restartPolicy: OnFailure
backoffLimit: 3
There are three patterns worth knowing. The first is the non-parallel Job, where completions is 1 and parallelism is 1, which is the default — the right shape for a migration, a one-off script, or a setup task. The second is the fixed-completion parallel Job shown above, where each Pod does an independent slice of the work and the Job completes when the count is reached. The third is the work-queue pattern, where completions is left unset and parallelism is set to a fixed number, and the Job runs until the queue is empty. In the work-queue pattern you need a way for Pods to know when there is no more work, usually by having each Pod check the queue and exit cleanly when it is drained. Without a reliable empty-queue signal this pattern can hang, so most teams start with fixed completions and move to a queue only when the workload genuinely needs it.
Indexed Jobs are a refinement of the fixed-completion pattern, available as a stable feature in recent Kubernetes versions. Setting completionMode: Indexed gives each Pod an index from zero to completions minus one, exposed through the JOB_COMPLETION_INDEX environment variable. Each Pod can use its index to claim a deterministic slice of the input — Pod 0 processes files 0 to 99, Pod 1 processes files 100 to 199, and so on — which removes the need for a shared queue entirely for workloads that can be partitioned by index. This is an elegant fit for data processing, test sharding and rendering jobs.
Choosing parallelism is a capacity question as much as a speed question. Ten Pods running at once consume ten times the CPU and memory of one Pod, and if each Pod opens connections to a database, ten Pods open ten times as many connections. A common production mistake is to set parallelism high without checking what the downstream systems can absorb. Start with a modest parallelism, watch the resource usage and the downstream services, and raise it gradually.
Retries, backoffLimit and activeDeadlineSeconds
Failures in batch work are normal, not exceptional. A network call times out, a database is briefly unavailable, or a node is drained mid-run. Jobs are designed around this reality, and the three fields that matter most are backoffLimit, activeDeadlineSeconds and restartPolicy.
backoffLimit sets the number of retries before the Job is marked Failed. Its default is 6, and it counts Pod failures, not container restarts within a Pod. With restartPolicy: OnFailure, a container that crashes is restarted inside the same Pod, and that restart does not count against backoffLimit until the Pod itself is considered failed. With restartPolicy: Never, every failed container creates a new Pod, and each new Pod counts against the limit. OnFailure is usually the better choice for transient errors, because restarting a container is cheaper than scheduling a new Pod, while Never gives you cleaner per-attempt logs.
Between retry attempts, the Job controller waits with exponential back-off. The first retry waits ten seconds, the next twenty, then forty, and so on up to a maximum of six minutes. This protects downstream systems from a tight retry loop and gives transient problems time to resolve. You cannot configure the back-off timing in the Job spec: the defaults are chosen to be safe, and if your workload needs different retry timing, that logic usually belongs in the application itself.
activeDeadlineSeconds is the safety net for Jobs that never finish. It sets a maximum wall-clock duration for the whole Job, from the moment the first Pod starts until the Job is terminated. If a Job exceeds its deadline, the controller kills its Pods and marks the Job Failed with a reason of DeadlineExceeded. This is essential for any Job that could hang: a process waiting forever on a network call, a queue consumer that never sees an empty queue, or a script stuck in an infinite loop. Without a deadline, a hung Job occupies cluster resources indefinitely. A sensible default is to set activeDeadlineSeconds to two or three times the expected runtime of the Job.
apiVersion: batch/v1
kind: Job
metadata:
name: nightly-report
spec:
activeDeadlineSeconds: 1800
backoffLimit: 3
template:
spec:
containers:
- name: report
image: registry.example.com/report-generator:2.1.0
command: ["python", "/app/generate_report.py"]
env:
- name: REPORT_DATE
value: "yesterday"
restartPolicy: OnFailure
This example gives the report Job thirty minutes to finish and three retries before failing. If it fails, the Job object records the failure reason, and kubectl describe job nightly-report shows the events and the count of failed Pods.
When a Job fails repeatedly, resist the urge to simply raise backoffLimit and re-run it. Persistent failures usually mean a bad image, a missing secret or ConfigMap, an unreachable service, or an input the application cannot handle. Check the Pod logs first, then the events on the Job, then the state of the dependencies. CrashLoopBackOff is the status you will see when a Pod keeps failing and the back-off delay grows, and the same debugging approach applies whether the Pod belongs to a Deployment or a Job. Our guide to fixing CrashLoopBackOff walks through the diagnosis step by step.
CronJobs and Schedules
A CronJob is a Job with a timetable. It creates a Job on a schedule you define, using the same five-field cron format that has been standard on Unix systems for decades: minute, hour, day of month, month, and day of week. A CronJob that runs a backup every night at 2 a.m. looks like this:
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-backup
spec:
schedule: "0 2 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: registry.example.com/backup-tool:3.0.1
command: ["sh", "-c", "pg_dump mydb | gzip > /tmp/mydb-$(date +%F).sql.gz"]
restartPolicy: OnFailure
backoffLimit: 2
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
The schedule field is the heart of the CronJob. The five fields are minute (0 to 59), hour (0 to 23), day of month (1 to 31), month (1 to 12), and day of week (0 to 7, where both 0 and 7 mean Sunday). “0 2 * * *” means 2:00 a.m. every day. “*/15 * * * *” means every fifteen minutes. “0 9 * * 1-5” means 9:00 a.m. on weekdays. The asterisks mean every value in that field, and the slash syntax means a step, so “0 */6 * * *” runs every six hours at the top of the hour. Quoting the schedule string is good practice because YAML can misinterpret values that start with an asterisk.
Time zones are a detail that catches many teams out. By default, the CronJob controller interprets schedules in the time zone of the kube-controller-manager, which in most managed clusters is UTC. If you want a schedule in a specific time zone, Kubernetes 1.27 and later support the timeZone field on the CronJob spec, and the feature is stable in 1.37. Setting timeZone: “America/New_York” makes “0 2 * * *” mean 2 a.m. Eastern time, including daylight saving transitions. If you are unsure what time zone your cluster uses, assume UTC and verify with a test CronJob that writes a timestamped log line.
Every time a CronJob fires, it creates a new Job object named after the CronJob plus a timestamp, and that Job runs its Pods exactly as a manually created Job would. This means all the Job behavior described earlier — completions, parallelism, backoffLimit, activeDeadlineSeconds — applies to CronJob runs as well, through the jobTemplate field.
Missed schedules have defined behavior. If the controller is down when a schedule fires, or if a previous run is still going, the CronJob checks the startingDeadlineSeconds field to decide whether the missed run is still worth starting. If startingDeadlineSeconds is set to 300, a run that was missed by more than five minutes is skipped rather than started late. This is the right default for most work: a backup that starts an hour late may be worse than no backup at all. Setting startingDeadlineSeconds to a sensible value — typically a few minutes — prevents a backlog of stale runs from piling up after an outage. The official CronJob documentation explains the scheduling mechanics, missed-run behavior and time zone support in full: Kubernetes CronJobs documentation.
Before relying on a CronJob in production, test it with a short schedule. Temporarily set the schedule to run every minute, confirm that Jobs are created and succeed, check the logs, and then restore the real schedule. This takes two minutes and catches most configuration errors — a wrong image tag, a missing volume, a bad command — before they matter.
Concurrency Policies and History Limits
Two CronJob fields control what happens when runs overlap and how much history the cluster keeps: concurrencyPolicy and the history limits. Both are worth setting deliberately rather than accepting the defaults.
concurrencyPolicy has three values. Allow is the default, and it lets a new Job start even if the previous run is still going. This is fine for idempotent work that can safely overlap, such as stateless report generation, but dangerous for anything that mutates shared state, such as a database migration or a file cleanup, where two concurrent runs can interfere with each other. Forbid skips a new run if the previous one is still active, which is the safe choice for most scheduled maintenance: the missed run is simply skipped, and the next scheduled run proceeds normally. Replace kills the currently running Job and starts a new one, which is useful when the newest run is always the one that matters — for example, a job that syncs data from an external system, where an old sync in progress is obsolete the moment a new one is due.
Which policy should you choose? Forbid is the right default for almost everything. It is the only policy that guarantees you never have two runs of the same task active at once, and the cost of a skipped run is usually small. Allow is appropriate when runs are independent and idempotent, and Replace is appropriate when a stale run is actively harmful. If you are unsure, choose Forbid and monitor whether runs are being skipped.
History limits control how many completed Job objects the CronJob keeps. successfulJobsHistoryLimit defaults to 3 and failedJobsHistoryLimit defaults to 1, and the controller deletes older Jobs once the limit is exceeded. Each retained Job keeps its Pods around, consuming etcd storage and cluttering kubectl output, but the history is also your debugging trail: when a run fails at 3 a.m., you want to inspect the failed Job and its logs. The defaults are reasonable, but for a job that runs every fifteen minutes, three successful Jobs only cover forty-five minutes of history. For high-frequency CronJobs, raising successfulJobsHistoryLimit to 5 or 10 is sensible, while keeping failedJobsHistoryLimit at 3 or higher gives you a useful window for investigating failures.
There is one more behavior worth knowing: CronJobs are not guaranteed to run exactly on time. The controller aims for the scheduled minute, but scheduling delays, API server load and node pressure can shift a run by seconds or more. For work that depends on precise timing — a report that must land at exactly 9 a.m. — a CronJob is the wrong tool, and you should trigger the work from an external scheduler instead.
Cleanup with ttlSecondsAfterFinished
Every completed Job leaves behind a Job object and its Pods, and by default they stay in the cluster forever. On a cluster with a handful of Jobs this is harmless. On a cluster where a CronJob runs every five minutes, it is a slow leak: after a week you have two thousand finished Jobs and their Pods sitting in etcd. The ttlSecondsAfterFinished field solves this by deleting a Job automatically after a defined delay.
apiVersion: batch/v1
kind: Job
metadata:
name: temp-cleanup
spec:
ttlSecondsAfterFinished: 3600
template:
spec:
containers:
- name: cleanup
image: busybox:1.36
command: ["sh", "-c", "find /data/tmp -type f -mtime +7 -delete"]
restartPolicy: Never
Setting ttlSecondsAfterFinished to 3600 means the Job and its Pods are deleted one hour after the Job finishes, whether it succeeded or failed. The delay is deliberate: it gives you a window to inspect the logs and the Job status after completion, and then the cluster cleans itself up. For a nightly report you might set a TTL of a day, so the previous night’s run is still inspectable in the morning. For a high-frequency job that runs every few minutes, a TTL of ten or fifteen minutes is usually enough.
There are two alternatives worth knowing. The first is manual deletion: kubectl delete job hello-job removes the Job and its Pods, and kubectl delete jobs –all removes every Job in the namespace, which is handy after a day of testing but dangerous in production. The second is the CronJob history limits described in the previous section, which cap how many Job objects a CronJob retains. These two mechanisms work together: history limits bound the number of Jobs kept, and the TTL bounds how long any individual Job is kept. For CronJobs, the TTL applies to each Job the CronJob creates, so a CronJob with ttlSecondsAfterFinished set in its jobTemplate gets automatic cleanup of every run.
A practical cleanup strategy for most teams looks like this. Set ttlSecondsAfterFinished on every Job and CronJob, with a value that matches how long you need the logs: an hour for routine jobs, a day for important nightly work. Set successfulJobsHistoryLimit to 3 and failedJobsHistoryLimit to 3 on CronJobs, and raise the failed limit on jobs where post-mortem debugging matters. Delete test Jobs promptly, and check kubectl get jobs across namespaces weekly to catch Jobs accumulating because someone forgot the TTL.
Frequently Asked Questions
What is the difference between a Kubernetes Job and a CronJob?
A Job runs a task once until it completes, while a CronJob creates Jobs on a recurring schedule. A CronJob that runs nightly creates a new Job object every night, and each of those Jobs behaves exactly like a manually created Job.
Can I use a Deployment instead of a Job for a one-off task?
Technically you can, but you should not. A Deployment restarts Pods that exit, so a task that completes successfully will be started again, and again, indefinitely. Jobs are designed for finite work: they track completions, count failures, and stop when the work is done. Use Deployments for services that should stay running, and Jobs for work that should finish.
Why does my Job keep failing with backoffLimit exceeded?
The message means the Job retried as many times as backoffLimit allows and still did not succeed. Check the Pod logs first with kubectl logs, then run kubectl describe job to see the events and failure counts. The most common causes are a bad image tag, a missing secret or ConfigMap, an unreachable database, or an application error on the input data.
How do I run a Job every day at a specific time?
Use a CronJob with a cron schedule. For 2 a.m. daily, set schedule to “0 2 * * *”. Remember that the schedule is interpreted in the controller’s time zone, usually UTC, unless you set the timeZone field.
How do I stop finished Jobs from piling up in my cluster?
Set ttlSecondsAfterFinished in the Job spec to delete the Job and its Pods automatically after a delay, such as 3600 seconds for one hour. For CronJobs, also set successfulJobsHistoryLimit and failedJobsHistoryLimit to cap how many past runs are retained.
Conclusion
Jobs and CronJobs are the quiet workhorses of Kubernetes. They do not serve traffic and they rarely get the attention that Deployments and Services receive, but they carry the batch work, migrations, backups, reports and cleanups that production systems depend on every day. The concepts are few — a Job runs until a defined amount of work completes, a CronJob creates Jobs on a schedule — but the details matter: completions and parallelism shape how fast a batch runs, backoffLimit and activeDeadlineSeconds decide how failures are handled, concurrency policies prevent overlapping runs from interfering with each other, and TTL-based cleanup keeps the cluster from drowning in finished work.
Start small. Write a Job that prints a message, watch it complete, and check its logs. Then convert one real scheduled task — a nightly backup, a weekly cleanup, a report — from a script on a server into a CronJob, with a Forbid concurrency policy, a sensible deadline and a TTL. Once that runs reliably for a week, you will have the confidence and the patterns to move the rest of your batch work into the cluster.



