Introduction to Jobs
In Kubernetes, a Job
creates one or more pods and ensures they successfully terminate. Jobs are useful for batch processing and tasks that are expected to terminate once completed.
Creating and Running Jobs
To create a Kubernetes Job, define its configuration in a YAML file.
Example YAML for a simple Job:
apiVersion: batch/v1
kind: Job
metadata:
name: example-job
spec:
template:
spec:
containers:
- name: example-container
image: busybox
command: ['sh', '-c', 'echo Hello from Kubernetes Job!']
restartPolicy: Never
Create the Job with kubectl
:
kubectl apply -f example-job.yaml
Monitoring Job Execution
To monitor the status of a running Job:
kubectl get jobs
To get more detailed information:
kubectl describe job example-job
Handling Failed Jobs
If a Job fails, you can inspect the pod to troubleshoot:
kubectl get pods --selector=job-name=example-job
kubectl logs <pod-name>
To delete a failed Job:
kubectl delete job example-job
CronJobs and Scheduled Tasks
A CronJob
runs Jobs on a time-based schedule.
Example YAML for a CronJob:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: example-cronjob
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: example-container
image: busybox
command: ['sh', '-c', 'date']
restartPolicy: OnFailure
Create the CronJob:
kubectl apply -f example-cronjob.yaml
List existing CronJobs:
kubectl get cronjobs
Exercise
Setup
- Save the example Job YAML to a file named
example-job.yaml
. - Save the example CronJob YAML to a file named
example-cronjob.yaml
.
Steps
- Create the Job:
kubectl apply -f example-job.yaml
- Monitor the Job:
kubectl get jobs
- Create the CronJob:
kubectl apply -f example-cronjob.yaml
- Monitor the CronJob:
kubectl get cronjobs
Troubleshooting
- Check pod logs:
kubectl logs <pod-name>
- Describe for more info:
kubectl describe job <job-name>
Solution
Make sure the Job and CronJob are successfully created and monitored.