Jobs in Kubernetes allow us to run one offs or recurring tasks using containers in our cluster. Common use cases for this are running one off reports from a database query, running tests during a CI/CD pipeline, or running cron jobs to send emails, cache data, and more. In this article, we will learn how to use Jobs in Kubernetes.
If you are here for the quick answer, here it is. Otherwise, continue to Getting Started.
Save the following to a file job.yaml
apiVersion: v1
kind: Job
metadata:
name: MyCronJob
spec:
schedule: h/30 * * * * ?
template:
metadata
name: py
spec:
containers:
- name: py
image: python
command: ["python", "index.py"]
restartPolicy: OnFailureThen use the following command.
kubectl apply -f job.yaml --namespace=my-example-namespaceWe will be working with minikube for most tutorials. This creates a local kubernetes cluster that you can develop on.
Feel free to use another kubernetes cluster for these tutorials as well. There will be articles underneath our kubernetes tags on how to run clusters on multiple providers such as AWS, Google Cloud, and Azure.
Once you have minikube installed, start the cluster using the following command.
minikube startTo create a job, we will first need a yaml file to store our job information. Create a new file
touch job.yamlNow, let's add the first two lines
apiVersion: v1
kind: JobThis states that we will use the apiVersion of version 1 and the kind of resource will be a job.
Next, let's add some metadata. This tell kubernetes to name our job and store it in a namespace. This helps for searching and managing our resources.
metadata:
name: my-job
namespace: my-example-namespaceNow we defined the spec for our job. There are two main fields, schedule, which represents the cron to run this if we are doing a cron job, and template which represents a pod spec.
spec:
schedule: h/30 * * * * ?
template:
metadata
name: py
spec:
containers:
- name: py
image: python
command: ["python", "index.py"]
restartPolicy: OnFailureNotice that we have one container, but we could add more. Now, our file should look like the following.
apiVersion: v1
kind: Job
metadata:
name: MyCronJob
spec:
schedule: h/30 * * * * ?
template:
metadata
name: py
spec:
containers:
- name: py
image: python
command: ["python", "index.py"]
restartPolicy: OnFailureNow, to deploy this job, we can use the following command, assuming your terminal is in the same directory as the file.
kubectl apply -f job.yaml --namespace= my-example-namespaceYou can view your job information using the following
kubectl get job my-job --namespace=my-example-namespace