Kubernetes CronJob Practical: Hands-On Tutorial with BusyBox & Scheduled Tasks

Practical Kubernetes CronJob tutorial with step-by-step examples, YAML configuration, kubectl commands, cron scheduling, and automated task execution using BusyBox.

CronJob Example

Download the YAML configuration file for the CronJob example

Download cronjob.yaml

Create the Job

kubectl apply -f cronjob.yaml

Applies the configuration from the YAML file to create the CronJob.

Get the Jobs List

kubectl get cronjobs

Lists all CronJobs in the current namespace.

Get More Info

kubectl describe cronjob

Shows detailed information about the CronJob.

Get the Pod Name

kubectl get pods

Get the pod's log. Something starting with hello-.

Get the Container's Log

kubectl logs <podName>

Get the container's log. You should see Hello from the Job.

Cleanup

kubectl delete -f cronjob.yaml

Deletes the CronJob and all related resources.

YAML Configuration File

apiVersion: batch/v1
kind: CronJob
metadata:
  name: hello-cron
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: busybox
            image: busybox
            command: ["echo", "Hello from the CronJob"]
          restartPolicy: Never

YAML Configuration Explanation:

CronJob Structure:

  • apiVersion: batch/v1 → Specifies the Kubernetes API version for CronJobs
  • kind: CronJob → Defines this as a CronJob resource
  • metadata.name: hello-cron → Names the CronJob "hello-cron"

Schedule Specification:

  • schedule: "* * * * *" → Cron format schedule (runs every minute)
  • The format is: minute (0-59) hour (0-23) day of month (1-31) month (1-12) day of week (0-7)
  • "* * * * *" means: every minute of every hour of every day

Job Template:

  • jobTemplate → Defines the Job that will be created when the CronJob runs
  • spec.template.spec → Standard Pod specification

Container Specification:

  • name: busybox → Names the container "busybox"
  • image: busybox → Uses the lightweight BusyBox image
  • command: ["echo", "Hello from the CronJob"] → Command to execute when the container starts

Restart Policy:

  • restartPolicy: Never → The container won't restart after completion
  • This is appropriate for Jobs that run once and complete

How It Works:

This CronJob will create a new Job every minute. Each Job will create a Pod that runs the BusyBox container, which executes the command to echo "Hello from the CronJob". After the command completes, the Pod terminates. The CronJob continues to create new Jobs according to the schedule until it's deleted.