Skip to main content

Jobs

Jobs are immutable except activeDeadlineSeconds, parallelism and completions.

Cmds
k get jobs
kubectl create job example-job --image=busybox --dry-run=client -o yaml > job.yaml
Job Manifest
apiVersion: batch/v1
kind: Job
metadata:
name: math-add-job
labels:
app: math
annotations:
description: "Performs simple parallel math tasks"
spec:
# Clean up this Job object (and its pods) 60 seconds after it finishes
ttlSecondsAfterFinished: 60

# Number of successful completions needed
completions: 3

# Maximum number of pods to run in parallel
parallelism: 3

# Maximum number of pod restarts per failed pod before giving up
backoffLimit: 4

# Total execution time (in seconds) allowed for the Job (including retries)
activeDeadlineSeconds: 120

# Pod template
template:
spec:
containers:
- name: math-add-container
image: busybox
command: ["/bin/sh", "-c", "echo 2+2 = $((2+2))"]
# For Jobs, restartPolicy must be OnFailure or Never
restartPolicy: OnFailure

CronJob

Cmds
k get cronjob
k create cronjob throw-dice-cron-job --image kodekloud/throw-dice -o yaml --dry-run=client --schedule "30 21 * * *" > c.yaml
CronJob Manifest
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: reporting-cron-job
labels:
app: reporting
annotations:
description: "This cron job runs a reporting task every minute."
spec:
schedule: "*/1 * * * *" # every minute

# Possible values: Allow (default), Forbid, or Replace
concurrencyPolicy: Forbid # at the CronJob level

# Retain N successful jobs for history
successfulJobsHistoryLimit: 3

# Retain N failed jobs for history
failedJobsHistoryLimit: 2


# If next scheduled time is missed by more than this number (seconds), skip it
startingDeadlineSeconds: 60

# If true, no new jobs are scheduled until set back to false
suspend: false

# ---- JOB TEMPLATE ----
jobTemplate:
metadata:
labels:
cronjob: "reporting"
spec:
# Maximum time (in seconds) a job can run before being terminated
activeDeadlineSeconds: 300

# Number of retries for a failing job
backoffLimit: 6

# Total completions needed
completions: 2

# Number of pods to run in parallel
# It works separately than concurrencyPolicy: Forbid
parallelism: 2 # Job-level. how many Pods are created concurrently by a single Job

# ---- POD SPEC (MINIMAL) ----
template:
spec:
containers:
- name: reporting-container
image: your-reporting-image:latest
# Simple example command
command: ["/bin/sh", "-c", "echo Hello from the CronJob!"]
# Typically OnFailure or Never for batch jobs
restartPolicy: OnFailure

If parallelism is more than completions: Kubernetes will launch up to 5 pods at once, but only 2 successful completions are needed to mark the Job as complete.