Basic usage of jobs
What are Kubernetes Jobs?
A Kubernetes job is a resource object that manages the execution of a single task to completion. It is used to run batch workloads, which are non-continuous processes that run for a specific period of time and then terminate. Jobs ensure that a specified number of pods successfully complete their tasks before terminating. If a pod fails, the job controller automatically creates a new pod to replace it, ensuring that the desired number of successful completions is achieved.
How do Kubernetes Jobs work?
When you create a Kubernetes job, you specify the number of successful completions required and the container image to use. Kubernetes then creates a pod that runs the specified container image and executes the command specified in the container’s entry point or command. The pod runs until the command completes successfully or fails. If the command fails, the pod is terminated, and a new pod is created to replace it. The job controller tracks the number of successful completions and terminates the job when the desired number is achieved.
create a job with kubectl
kubectl create -f job.yaml
view the status of a job with kubectl
kubectl get jobs
kubectl describe job <job-name>
delete a job with kubectl
kubectl delete job <job-name>
run jobs in parallel
use parallelism to run jobs in parallel
apiVersion: batch/v1
kind: Job
metadata:
name: job-counter
spec:
parallelism: 3
template:
metadata:
name: job-counter
spec:
restartPolicy: Never
containers:
- name: counter
image: busybox
command:
- "bin/sh"
- "-c"
- "for i in 9 8 7 6 5 4 3 2 1; do echo $i; done"
run cron jobs
use schedule to run cron jobs
apiVersion: batch/v1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
command: ["echo", "hello cron job"]
restartPolicy: OnFailure
kubectl get cronjob hello
kubecti get jobs --watch
or run cron jobs with kubectl
kubectl run hello --schedule="*/1 * * * *" --restart=OnFailure --image=busybox -- /bin/sh -c "date; echo Hello from the Kubernetes cluster"