Kubernetes CronJob and Job YAML example
A Job runs Pods until they finish successfully, which suits one-off work like a database migration. A CronJob creates a new Job on a schedule written in standard cron syntax.
The fields that matter most are restartPolicy (it must be OnFailure or Never), backoffLimit (how many retries before the Job is marked failed) and, for a CronJob, the history limits that stop finished Jobs from piling up.
What this manifest does
This manifest defines 3 resources in the batch namespace: the main thing it runs are 1 Job and 1 CronJob. Let’s walk through it.
Job db-migrate runs to completion (1 time), running myorg/migrate:v12.3.
CronJob nightly-backup runs on the schedule 0 2 * * *, running myorg/backup:1.4.0.
It reads its configuration from ConfigMap backup-config.
Things to know before using it
Container may run as rootJob db-migrate, CronJob nightly-backup
Container "migrate" doesn't enforce runAsNonRoot. A compromise gives the attacker root inside the container. Fix: Set securityContext.runAsNonRoot: true and runAsUser to a non-zero UID.
allowPrivilegeEscalation not setJob db-migrate, CronJob nightly-backup
Container "migrate" doesn't explicitly disable privilege escalation. Defaults to true on older kubelets. Fix: Set securityContext.allowPrivilegeEscalation: false.
Writable root filesystemJob db-migrate, CronJob nightly-backup
Container "migrate" doesn't set readOnlyRootFilesystem. Attackers can write tools into / at runtime. Fix: Set securityContext.readOnlyRootFilesystem: true and use volumeMounts for paths that need write access (/tmp, /var/run, ...).
Linux capabilities not droppedJob db-migrate, CronJob nightly-backup
Container "migrate" doesn't drop ALL capabilities. By default it runs with ~14 caps including NET_RAW, MKNOD. Fix: Set securityContext.capabilities.drop: ["ALL"] and add only what you need under capabilities.add.
The full manifest
# Batch workloads — a one-off Job and a scheduled CronJob.
apiVersion: v1
kind: ConfigMap
metadata:
name: backup-config
namespace: batch
data:
S3_BUCKET: my-backups
---
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
namespace: batch
spec:
completions: 1
parallelism: 1
backoffLimit: 3
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: myorg/migrate:v12.3
command: ["./migrate", "up"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
---
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-backup
namespace: batch
spec:
schedule: "0 2 * * *"
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: myorg/backup:1.4.0
envFrom:
- configMapRef:
name: backup-config
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: 1
memory: 512Mi
Related examples
Stuck on a Kubernetes concept?
Ask anything and get a narrated visual lesson, pitched at your level. Free.
Try an example