🎓 A1Learner
🔍
0 of 51 lessons completed

Kubernetes: Jobs and CronJobs

A Job is a workload that runs a task once to completion. A CronJob is a Job that runs on a schedule. It works like a clock that starts a Job at a set time.

A Job that runs once

The Job runs one container. The container prints two lines and stops. restartPolicy Never means a finished Pod stays finished.

apiVersion: batch/v1
kind: Job
metadata:
  name: backup
spec:
  template:
    spec:
      containers:
      - name: backup
        image: nginx:1.27-alpine
        command: ["sh", "-c", "echo backing up data && echo backup done"]
      restartPolicy: Never

Start the Job

apply creates the Job. The Job then creates one Pod to do the work.

kubectl apply -f backup-job.yaml

Check the Job finished

Complete means the task ran once and finished. 1/1 means the one wanted run is done.

kubectl get jobs

The same task, every night

The schedule 0 2 * * * means 2 in the morning, every day. The CronJob starts a fresh Job at that time.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-backup
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: nginx:1.27-alpine
            command: ["sh", "-c", "echo backing up data && echo backup done"]
          restartPolicy: Never

See the schedule

get cronjobs shows the schedule and the last run. Suspend False means the schedule is live.

kubectl get cronjobs

Example

kubectl apply -f backup-job.yaml
kubectl get jobs
kubectl get pods
kubectl logs job/backup

Key points

  • Job: a workload that runs a task once, then stops when the task finishes.
  • Use a Job for a backup, a data load or a one-off report.
  • CronJob: a Job that runs on a schedule, stated in cron form.
  • Use a CronJob for a nightly backup or a daily cleanup.
  • A Job creates Pods, and the Pods stop when the work is done.
  • restartPolicy: the rule that says whether a stopped container starts again.
  • A failed Job can retry, and the retry count is set in the manifest.

In this example, apply creates a Job that runs one backup task. get jobs shows one completion. get pods shows the Pod completed. logs shows the task output. The Job ran once and stopped, which is the point of a Job.

Note

A Deployment keeps Pods running, while a Job lets its Pods finish and stop.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Which workload runs a task once to completion and then stops?