Let's run a Job that doesn't nothing but sleep for a minute:
apiVersion: batch/v1
kind: Job
metadata:
name: sleep-on-the-job
spec:
template:
metadata:
labels:
app.kubernetes.io/name: sleep-on-the-job
spec:
restartPolicy: Never
containers:
- name: sleep-container
image: busybox
args:
- sleep
- "60"
Save the above YAML in sleep-job.yaml
and run kubectl apply -f sleep-job.yaml
to create the Job.
NOTE: We are explicitly setting the restartPolicy
to Never. The default value for restartPolicy
is Always, however, the Job resource does not support that restart policy. The two supported values are Never and OnFailure. Setting one of these values prevents the container from being restarted when it finishes running.
You can list the Job the same way as any other resource. Notice how the output also shows the number of completions of the Job and duration of the Job.
$ kubectl get job
NAME COMPLETIONS DURATION AGE
sleep-on-the-job 0/1 4s 4s
If you describe the Job you will notice in the Events section that controller creates a Pod to run the Job:
$ kubectl describe job sleep-on-the-job
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal SuccessfulCreate 18s job-controller Created pod: sleep-on-the-job-f9ht8
...
Let's look at the Pod that was created by this Job. We will use the -labels
flag to get all Pods with the label app.kubernetes.io/name=sleep-on-the-job
:
$ kubectl get pods -l=app.kubernetes.io/name=sleep-on-the-job
NAME READY STATUS RESTARTS AGE
sleep-on-the-job-f9ht8 1/1 Running 0 48s
After a minute, the Pod will stop running, however, it won't be deleted. If you run the same command as above, you will notice that the Pod is still around. Kubernetes keeps the Pod around so you can look at the logs, for example.
$ kubectl get pods -l=app.kubernetes.io/name=sleep-on-the-job
NAME READY STATUS RESTARTS AGE
sleep-on-the-job-f9ht8 0/1 Completed 0 28m
Similarly happens with the Job resource. The resource stays around until you explicitly delete it. Deleting the Job also deletes the Pod. Notice how the number of completions now shows 1/1
, which means that the Job was completed successfully one time.
$ kubectl get job
NAME COMPLETIONS DURATION AGE
sleep-on-the-job 1/1 63s 12m
If you're wondering if a job can be completed and executed multiple times, the answer is yes, it can. The Job can track the number of successful completions, and you can use that number as to control when the Job completes.