Cron Jobs in Kubernetes

A lot of time, we need to run periodic jobs using Cron. Kubernetes is an amazing tool for it since it simplifies resource management by spinning up nodes in case of non availability of resources and releasing them in case of excess capacity.

Cron jobs can be deployed by referring to the below sample yaml and running kubectl apply -f

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: cron-job
  namespace: "${namespace}"
spec:
  schedule: "0/30 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: cron-jobs
            image: "${repo}:${DRONE_BUILD_NUMBER}"
            env:
              - name: run_environment
                value: ${run_environment}
          restartPolicy: OnFailure

This runs the cron job every 30 minutes

Notes

  • Use envsubst to replace env variables in .yml file
  • Install it in debian using command apt-get install gettext -y
  • Run the deploy in CI/CD using the command cat deploy.yml|envsubst|kubectl apply -f -
  • We set restartPolicy: OnFailure so that, it doesn't keep on restarting the job on completion of it.

Subscribe to Blog

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe