Running A cronjob in a pod in Kubernetes
Unfortunately, you cannot run the CronJob inside a container of your application.
The only thing you can do is create a container which will contain your cronjob and necessary environment for running it and schedule to run that pod by a CronJob.
Here is an example of the configuration:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *" # syntax is a same as in system cron jobs
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: image_with_cronjob_code # here is an image with your cronjob
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
Anshul Tripathi
Updated on June 04, 2022Comments
-
Anshul Tripathi over 1 year
I have a backend nodeJS application running in a kubernetes cluster. Now I want to run two cron jobs to be scheduled every month. The cron jobs are in a JS file. How do I create a job that runs those JS files in the pod running that service every month using Kubernetes ?
This link gives a basic understanding of how it works but I am a little confused on how to run it for a specific service and on a specific pod
https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#writing-a-cron-job-spec -
Hiruma over 5 yearsTechnically you can, it's just a bad idea :) Also worth mentioning: CronJob not enabled by default below Kubernetes 1.8.
-
Anshul Tripathi over 5 yearsMy use case is that I have an application running on a kubernetes cluster and it has to fetch data from the database once every month. That application already has the JS code for fetching the data. I just want to know if it is possible for the existing service to do that using cronjob in Kubernetes and if so how is that possible.
-
Anton Kostenko over 5 yearsPod and container in it, where your application running is not a persistent item. It can be restarted at any time by Scheduler, on a cluster updating, etc. And because of that, you will lose all fetched data. So, the best way in your situation is to rebuild a container every month and update application in the cluster. Updating can be easily done by Kubernetes.
-
Anshul Tripathi over 5 yearsThe service doesn't store the data locally. I just have to pull the data every 15th of the month from this application and store it in an external database. As long as that script gets executed it is fine. What would be the quickest way to go about it ?
-
Anshul Tripathi over 5 yearsAlso right now for the application I do a deployment and a service. Will just running the application as a cronjob work ?
-
Anton Kostenko over 5 yearsYes, it will stop right after job done, because Kubernetes will wait until all processes in a container are stopped.