Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

Running Automated Tasks with a CronJob over Kubernetes running on Docker Desktop

3 min read

Docker Desktop 4.1.1 got released last week. This latest version support Kubernetes 1.21.5 that was made available recently by the Kubernetes community. There were couple of new features announced with this latest version of Kubernetes. For example, CronJobs graduated to the stable version for the first time, Immutable Secrets and ConfigMaps graduated (Secrets and ConfigMaps by default are mutable which is beneficial for pods that are able to consume changes but Mutating Secrets and ConfigMaps can also cause problems if a bad configuration is pushed for pods that use them) with this latest release, IPv4/IPv6 dual-stack support was introduced (dual-stack support in Kubernetes means that pods, services, and nodes can get IPv4 addresses and IPv6 addresses. In Kubernetes 1.21 dual-stack networking has graduated from alpha to beta, and is now enabled by default.) etc. You can find the list of all the new features introduced under this link.

Docker Desktop is FREE for personal use

Yes, you read it correct. Docker Desktop remains free for small businesses (fewer than 250 employees AND less than $10 million in annual revenue), personal use, education, and non-commercial open source projects. The existing Docker Free subscription has been renamed Docker Personal. No changes to Docker Engine or any other upstream open source Docker or Moby project.


CronJob graduated to Stable!

CronJobs was promoted to general availability in Kubernetes v1.21 for the first time. Older Kubernetes versions do not support the batch/v1 CronJob API. CronJobs are meant for performing regular scheduled actions such as backups, report generation, and so on. Each of those tasks should be configured to recur indefinitely (for example: once a day / week / month); you can define the point in time within that interval when the job should start.

To test-drive CronJob feature of Kubernetes, let us quickly leverage Docker Desktop. You can refer this link to download Docker Desktop for Mac. Once you install Docker Desktop, go to Preference tab as shown in the image.

Select “Kubernetes” tab and click on “Enable Kubernetes” box.

Verifying Kubectl version:

kubectl version --short
Client Version: v1.21.5
Server Version: v1.21.5

Checking the Kubernetes Component Status


kubectl get --raw '/healthz?verbose'
[+]ping ok
[+]log ok
[+]etcd ok
[+]poststarthook/start-kube-apiserver-admission-initializer ok
[+]poststarthook/generic-apiserver-start-informers ok
[+]poststarthook/priority-and-fairness-config-consumer ok
[+]poststarthook/priority-and-fairness-filter ok
[+]poststarthook/start-apiextensions-informers ok
[+]poststarthook/start-apiextensions-controllers ok
[+]poststarthook/crd-informer-synced ok
[+]poststarthook/bootstrap-controller ok
[+]poststarthook/rbac/bootstrap-roles ok
[+]poststarthook/scheduling/bootstrap-system-priority-classes ok
[+]poststarthook/priority-and-fairness-config-producer ok
[+]poststarthook/start-cluster-authentication-info-controller ok
[+]poststarthook/aggregator-reload-proxy-client-cert ok
[+]poststarthook/start-kube-aggregator-informers ok
[+]poststarthook/apiservice-registration-controller ok
[+]poststarthook/apiservice-status-available-controller ok
[+]poststarthook/kube-apiserver-autoregistration ok
[+]autoregister-completion ok
[+]poststarthook/apiservice-openapi-controller ok
healthz check passed

Test driving CronJobs

CronJobs (previously ScheduledJobs), is used primarily for performing regular scheduled actions such as backups, report generation, and so on, has been a beta feature since Kubernetes 1.8! With 1.21, we get to finally see this widely used API graduate to stable. A CronJob creates Jobs on a repeating schedule. One CronJob object is like one line of a crontab (cron table) file. It runs a job periodically on a given schedule, written in Cron format. In addition, the CronJob schedule supports timezone handling, you can specify the timezone by adding “CRON_TZ=” at the beginning of the CronJob schedule, and it is recommended to always set CRON_TZ.

Most often, I use Cronitor – a quick and simple editor for cron schedule expressions by Cronitor.

Let us try to write a CronJob manifest that prints the current time and a hello message every minute:

Create a file called crontest.yaml and add the below content:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: crontesting
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kube cluster
          restartPolicy: OnFailure

Running the CronJob

kubectl create -f crontest.yaml 
cronjob.batch/crontesting created

Fetching the status

kubectl get cronjob crontesting
NAME          SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
crontesting   */1 * * * *   False     0        <none>          28s

You can further fetch the status over Docker Desktop Dashboard UI too as shown below:

As you can see from the results of the command, the cron job has not scheduled or run any jobs yet. Watch for the job to be created in around one minute:

Watching the Job

kubectl get jobs --watch
NAME                   COMPLETIONS   DURATION   AGE
crontesting-27250869   1/1           1s         43s
crontesting-27250870   0/1                      0s
crontesting-27250870   0/1           0s         0s
crontesting-27250870   1/1           1s         1s

Now you’ve seen one running job scheduled by the “crontesting” cron job. You can stop watching the job and view the cron job again to see that it scheduled the job:

kubectl get cronjob crontesting
NAME          SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
crontesting   */1 * * * *   False     0        8s              3m4s

You should see that the cron job crontesting successfully scheduled a job at the time specified in LAST SCHEDULE. There are currently 0 active jobs, meaning that the job has completed or failed.

Deleting a Cron Job

When you don’t need a cron job any more, delete it with kubectl delete cronjob <cronjob name>:

kubectl delete cronjob crontesting

Also Read:

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

Platform Engineering vs DevOps vs SRE: A Cheatsheet

According to Gartner®, by 2026, 80% of large software engineering organizations will establish platform engineering teams—a significant leap from 45% in 2022. This shift...
Tanvir Kour
2 min read

How to Develop Event-Driven Applications with Kafka and Docker

Event-driven architectures have become increasingly popular with the rise of microservices. These architectures are built around the concept of reacting to events in real-time,...
Abraham Dahunsi
6 min read

Comments are closed.

Join our Discord Server
Index