What's a Kubernetes Job?

2 min read

A Kubernetes Job is an object that contains a Pod definition, just as a Deployment do, but instead of expecting the Pod to be continuously running, it is expecting it to finish. In case the Pod execution fails, it will continue to retry execution until a specified number of them successfully terminate.

Similarly as we do with deployments, we must specify a selector in order to let the Job know which Pods is controlling, so if we are using matchLabels we must specify them on the Pod template.

As Pods successfully complete, the Job tracks the successful runs and when a specified number of successful completions is reached, the Job is considered complete.

If we have a non-parallel Job: We want to run a single Pod, we can leave both completions and parallelism unset, since their default value is 1

If we can have several Pods running concurrently we can specify a different number for parallelism (how many we want to have running at the same time) and completions (how many must complete succesfully to consider this Job completed)

We can also set the number of retries we want to allow for a Job before considering it failed. To do so we can use backoffLimit

A sample Job definition would look like follows:

apiVersion: batch/v1
kind: Job
metadata:
  name: test
spec:
  backoffLimit: 5
  selector:
    matchLabels:
      job-name: test
  template:
    metadata:
      labels:
        job-name: test
    spec:
      containers:
      - name: test
        command:
        - sleep
        - 5m
        image: busybox

We can also create jobs imperatively by using kubectl create job

$ kubectl create job test -o yaml --image busybox -- sleep 5m

Using kubectl get jobs we can get the list of jobs:

$ kubectl get jobs
NAME                                     COMPLETIONS   DURATION   AGE
test                                     0/1           12s        13s

Posted on 05/08/2021

Categories