Jobs and CronJobs

Kubernetes · lesson 17 of 32 · 3 min read

Run work that is supposed to finish: migrations, nightly reports, scheduled cleanups.

Open this lesson in the learning hub

Key points

  • A Job runs a pod until it exits 0. A Deployment restarts forever; a Job is finished when the work is finished.
  • backoffLimit caps retries and activeDeadlineSeconds caps wall clock. Without both, a broken Job retries all night.
  • completions with parallelism fans the same work out across several pods at once.
  • A CronJob creates a Job on a schedule. It runs in UTC unless you set timeZone, which catches people out twice a year.
  • concurrencyPolicy: Forbid skips a run while the previous one is still going. The default Allow lets them pile up.
  • Set ttlSecondsAfterFinished or history limits, or completed pods sit in the namespace for months.

Example

apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "0 2 * * *"
  timeZone: "Europe/London"        # without this, 02:00 UTC
  concurrencyPolicy: Forbid        # never two runs at once
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 2              # 3 attempts, then Failed
      activeDeadlineSeconds: 3600  # hard stop after an hour
      ttlSecondsAfterFinished: 86400
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: report
              image: ghcr.io/acme/reports:1.4.2
              args: ["--for", "yesterday"]

A Job is work that ends. Give it a retry cap and a deadline or it never will.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Kubernetes course, and every lesson in it is listed on the Kubernetes contents page.