How to Create a Job in Kubernetes: Step-by-Step Guide
To create a
Job in Kubernetes, define a YAML manifest specifying apiVersion, kind: Job, metadata, and a spec with a pod template. Apply this YAML using kubectl apply -f filename.yaml to run one or more pods that complete a task.Syntax
A Kubernetes Job manifest includes these main parts:
- apiVersion: The API version, usually
batch/v1. - kind: Must be
Jobto create a job resource. - metadata: Name and labels for the job.
- spec: Defines the job behavior, including
templatefor pod specs. - template: Describes the pod to run, including containers and commands.
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: example-job
spec:
template:
spec:
containers:
- name: example
image: busybox
command: ["/bin/sh", "-c", "echo Hello Kubernetes! && sleep 30"]
restartPolicy: NeverExample
This example creates a job that runs a simple command in a busybox container and then exits.
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: hello-job
spec:
template:
spec:
containers:
- name: hello
image: busybox
command: ["/bin/sh", "-c", "echo Hello Kubernetes! && sleep 5"]
restartPolicy: NeverOutput
job.batch/hello-job created
NAME COMPLETIONS DURATION AGE
hello-job 1/1 5s 10s
Common Pitfalls
Common mistakes when creating Kubernetes Jobs include:
- Setting
restartPolicytoAlwaysinstead ofNeverorOnFailure, which causes pods to restart indefinitely. - Not specifying a
commandorargsin the container, leading to immediate pod exit. - Forgetting to apply the YAML file with
kubectl apply -f.
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: wrong-job
spec:
template:
spec:
containers:
- name: wrong
image: busybox
# Missing command causes pod to exit immediately
restartPolicy: Always # Wrong restart policy for jobs
---
apiVersion: batch/v1
kind: Job
metadata:
name: correct-job
spec:
template:
spec:
containers:
- name: correct
image: busybox
command: ["/bin/sh", "-c", "echo Fixed command"]
restartPolicy: NeverQuick Reference
| Field | Description | Example |
|---|---|---|
| apiVersion | API version for Job resource | batch/v1 |
| kind | Resource type | Job |
| metadata.name | Name of the job | hello-job |
| spec.template.spec.containers | Containers to run | busybox with command |
| spec.template.spec.restartPolicy | Pod restart policy | Never or OnFailure |
| spec.completions | Number of successful completions (optional) | 1 |
| spec.parallelism | Number of pods to run in parallel (optional) | 1 |
Key Takeaways
Define a Job with kind: Job and apiVersion: batch/v1 in a YAML file.
Set restartPolicy to Never or OnFailure to avoid infinite pod restarts.
Use kubectl apply -f your-job.yaml to create the job in the cluster.
Specify the container command to ensure the pod runs the intended task.
Check job status with kubectl get jobs and kubectl describe job .