0
0
KubernetesHow-ToBeginner · 3 min read

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 Job to create a job resource.
  • metadata: Name and labels for the job.
  • spec: Defines the job behavior, including template for 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: Never
💻

Example

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: Never
Output
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 restartPolicy to Always instead of Never or OnFailure, which causes pods to restart indefinitely.
  • Not specifying a command or args in 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: Never
📊

Quick Reference

FieldDescriptionExample
apiVersionAPI version for Job resourcebatch/v1
kindResource typeJob
metadata.nameName of the jobhello-job
spec.template.spec.containersContainers to runbusybox with command
spec.template.spec.restartPolicyPod restart policyNever or OnFailure
spec.completionsNumber of successful completions (optional)1
spec.parallelismNumber 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 .