Jobs and CronJobs

Topics Covered

Jobs: Run to Completion

Creating a Job quickly

Completions and parallelism

Indexed Jobs

Watching a Job

Choosing between Never and OnFailure

Jobs and the pod template

What the grader checks

Speed habits for Job tasks

A Deployment keeps pods running forever. A Job runs pods until a number of them finish successfully, then stops. Database migrations, report generation, batch data processing and one off maintenance scripts are all Jobs. The exam uses Jobs and CronJobs because they are compact, have many fields with precise meanings, and are easy to verify: either the Job reached Complete with the right number of successes, or it did not. This lesson walks through the fields in the order you meet them in tasks, then spends a full section on debugging, which is where most real time goes.

Creating a Job quickly

The imperative command gets you a working Job, or a skeleton to edit, in one line.

bash
kubectl -n batch create job pi --image=perl:5.40 -- perl -Mbignum=bpi -wle 'print bpi(200)'
kubectl -n batch create job hello --image=busybox:1.36 --dry-run=client -o yaml \
  -- sh -c 'echo hello; sleep 5' > hello.yaml

Everything after -- becomes the container's command. The generated manifest looks like this, trimmed:

yaml
1apiVersion: batch/v1
2kind: Job
3metadata:
4  name: hello
5  namespace: batch
6spec:
7  template:
8    spec:
9      containers:
10      - name: hello
11        image: busybox:1.36
12        command: ["sh", "-c", "echo hello; sleep 5"]
13      restartPolicy: Never

Two details matter. First, restartPolicy must be Never or OnFailure. The default for a pod is Always, which makes no sense for a task that should end, and the API server rejects a Job with it. Second, kubectl run with --restart=Never creates a bare pod, not a Job. If the task says "create a Job", use kubectl create job, because the grader checks the object kind.

The Job controller adds a selector and labels for you: pods get batch.kubernetes.io/job-name=hello and a controller-uid label tied to the Job. You rarely set the selector yourself, and setting manualSelector: true is almost never what a task wants.

Completions and parallelism

Two numbers shape a Job's work.

  • completions: how many pods must exit successfully before the Job is complete. Default 1.
  • parallelism: how many pods may run at the same time. Default 1.

These give three common patterns. A single pod Job leaves both at 1. A fixed completion count Job sets completions to N and parallelism to how many you can afford at once: with completions: 6 and parallelism: 2, the controller keeps two pods running and starts another each time one succeeds, until six have succeeded. A work queue Job leaves completions unset and sets parallelism. The pods pull items from a queue and exit when the queue is empty; the Job is complete when any pod succeeds and all pods have stopped.

With completions 6 and parallelism 2, the Job runs two pods at a time until six have succeeded.
yaml
1spec:
2  completions: 6
3  parallelism: 2
4  template:
5    spec:
6      restartPolicy: Never
7      containers:
8      - name: worker
9        image: busybox:1.36
10        command: ["sh", "-c", "echo processing; sleep 10"]

There is no imperative flag for completions or parallelism on kubectl create job, so generate the skeleton and add the fields. You can change parallelism on a running Job by patching spec.parallelism with kubectl patch job NAME --type=merge or with kubectl edit job NAME, and the controller adjusts the number of running pods. completions is immutable once the Job exists, except for Indexed Jobs where it can be changed together with parallelism to grow or shrink the work.

Indexed Jobs

By default, the pods of a Job are interchangeable: any pod can succeed and count toward completions. With completionMode: Indexed, each pod receives a distinct index from 0 to completions - 1, and the Job is complete when every index has one successful pod.

yaml
1spec:
2  completions: 3
3  parallelism: 3
4  completionMode: Indexed
5  template:
6    spec:
7      restartPolicy: Never
8      containers:
9      - name: shard
10        image: busybox:1.36
11        command: ["sh", "-c", "echo processing shard $JOB_COMPLETION_INDEX"]

The index is available three ways: the environment variable JOB_COMPLETION_INDEX, the annotation batch.kubernetes.io/job-completion-index, and the pod's hostname, which takes the form JOBNAME-INDEX. If a pod for index 1 fails, the replacement pod gets index 1 again, so each shard is processed exactly once to success. This is the clean way to split a fixed data set into N pieces without an external queue.

Indexed completion mode gives each pod a stable index from 0 to completions minus 1.

Watching a Job

The quickest checks are the Job's own status and its pods.

bash
1kubectl -n batch get job hello
2# NAME    STATUS     COMPLETIONS   DURATION   AGE
3# hello   Complete   1/1           8s         20s
4kubectl -n batch get pods -l batch.kubernetes.io/job-name=hello
5kubectl -n batch logs job/hello
6kubectl -n batch wait --for=condition=complete job/hello --timeout=120s

kubectl logs job/NAME picks one of the Job's pods, which is enough for a single pod Job. For a parallel Job, list the pods and read each one, or use the label selector with kubectl logs -l batch.kubernetes.io/job-name=NAME --prefix. kubectl wait is useful in a task that says "the Job must have completed", because it blocks until the condition is true or the timeout expires, and its exit code tells you which.

Choosing between Never and OnFailure

The two restart policies behave differently when a container fails, and it changes what you see when you debug.

With restartPolicy: Never, a failed container leaves its pod in the Failed phase, and the Job controller creates a new pod for the retry. You end up with several pods, one per attempt, and each failed pod keeps its logs. With restartPolicy: OnFailure, the kubelet restarts the container inside the same pod, and the pod's restart count climbs. You see one pod, and kubectl logs --previous shows the last failed attempt.

For debugging, Never is friendlier, because every attempt is preserved. For node resource use, OnFailure is lighter. Both count toward backoffLimit, which the next section covers. If a task does not specify, Never is a safe default and matches what kubectl create job generates.

Jobs and the pod template

Everything you know about pod specs from lesson three applies inside spec.template.spec: resources, env from ConfigMaps and Secrets, volumes, ServiceAccounts and security contexts. A Job in a namespace with a ResourceQuota on requests still needs requests set, or its pods are refused. The difference from a Deployment is that the pod template of a Job is immutable after creation for most fields. If a Job has the wrong image or command, delete it and create a corrected one rather than trying to edit it in place.

bash
kubectl -n batch delete job hello
kubectl -n batch apply -f hello.yaml

Deleting a Job deletes its pods too, because they are owned by the Job. That is usually what you want after a mistake. If you need to keep the pods for evidence, add --cascade=orphan, but remember to clean them up afterwards so they do not count against the namespace pod quota.

What the grader checks

For a Job task, the grader typically checks three things: the object exists in the right namespace with the right name, specific fields match the task (image, command, completions, parallelism), and the Job finished as expected. Read the task again before you submit and compare each requirement to kubectl get job NAME -o yaml. A Job that completes successfully but uses busybox:latest when the task said busybox:1.36 can lose the whole task.

Speed habits for Job tasks

Job tasks reward a fixed routine. Switch context, generate the skeleton with --dry-run=client -o yaml, add the spec level fields, apply, then wait and verify. Keep the generated file: if the Job fails, you will delete it and apply a corrected copy, and editing a file you already have is faster than regenerating it. Name files after the task number, such as q7-job.yaml, so you can find them again when you review flagged tasks at the end of the exam.

When the command is long or contains quotes, write it as sh -c '...' with single quotes around the script and double quotes inside it. That keeps your own shell from expanding variables, and it keeps the YAML generator from splitting the script into separate arguments in unexpected places. Check the generated command list before you apply.

Generate the Job, then add the numbers

kubectl create job has no flags for completions, parallelism or backoffLimit. Generate with --dry-run=client -o yaml, add the fields under spec, not under spec.template.spec, and apply. Putting them in the pod spec is the most common placement mistake.