Kubernetes - Jobs

Kubernetes jobs

In Kubernetes, A job is use to execute a finite task. Some examples are sending emails, transcoding files, scanning database keys, etc.

Job

job.yaml - a sample job

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
apiVersion: batch/v1
kind: Job
metadata:
name: hellojob
spec:
template:
metadata:
name: hellojob
spec:
containers:
- name: hello
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: Never

Jobs are executed using kubectl apply command

1
kubectl apply -f job.yaml

use kubectl get pod command to get the pod name and then use kubectl logs command to see the output.

1
2
3
4
5
6
7
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
hellojob-hfc2h 0/1 Completed 0 10s

$ kubectl logs hellojob-hfc2h
Sat Sep 28 20:23:47 UTC 2019
Hello from the Kubernetes cluster

use kubectl delete cron hellojob to delete the job.

Parallel Jobs

The above job execute only once. You can have the job execute multiple times in parallel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
apiVersion: batch/v1
kind: Job
metadata:
name: hellojob
spec:
parallelism: 2
completions: 3
template:
metadata:
name: hellojob
spec:
containers:
- name: hello
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: Never

Here the job is execute 3 times with 2 pods executing in parallel.

We can examine the jobs that is completed.

1
2
3
$ kubectl get jobs
NAME COMPLETIONS DURATION AGE
hellojob 3/3 4s 26s

use kubectl delete cron hellojob to delete the job.

CronJob

CronJob runs on a schedule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hellojob
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
metadata:
name: hellojob
spec:
containers:
- name: hello
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: Never

A pod is spin up to run the cronjob every minute.

Use kubectl get cronjobs command to see the cronjob

1
2
3
$ kubectl get cronjobs
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE
hellojob */1 * * * * False 0 <none> 11s

use kubectl delete cronjob hellojob to delete the cronjob.

References