NestJS Kubernetes Deployment | Part 4: Kubernetes CronJob — NestJS
Deploying NestJS applications on the Kubernetes Cluster series is divided into two main and two follow-up stories.
Part 1: Containerizing a NestJS application with Docker
Part 2: Kubernetes Deployment
Part 3: Bonus: Ingress Configuration
Part 4: Bonus: Kubernetes CronJob — NestJS
This is a bonus part of the NestJS Kubernetes Deployment Series.
Task scheduling features of NestJS are not used in this story.
Roadmap:
- Adding shutdown capability to the NestJS application.
- Configuring and applying the cronjob.
A demo application is provided at the end of the story.
Getting Started 🍼
Install NestJS Config if not already installed.
Append CRONJOB=CRONJOB to your .env file. This will allow running the application conditionally. When the CRONJOB environment variable is present, the app will run the required service and shut down.
Update the related service with the following code.
Update the main.ts file with the following logic.
If the app is run with the CRONJOB variable, the foo function inside the app service will be called. Once it is finished, a shutdown event will be triggered.
Build version 0.0.3 image with the new changes. (see part1 to build the image)
Create Your cronjob.yaml file 🔧
Run the following command to create the cronjob. See Troubleshooting/Notes at the end of the article.
$ kubectl apply -f cronjob.yaml
This cronjob will create a job every minute and use the demo:0.0.3 application.
Depending on the need and the code, there is a chance of draining the cluster because of jobs running concurrently. To prevent that, the following limitations are used.
If concurrencyPolicy is set to Forbid and a previous schedule is still running, a new job will not be created and will be counted as missed.
For every CronJob, the CronJob Controller checks how many schedules it missed in the duration from its last scheduled time until now. If there are more than 100 missed schedules, then it does not start the job. startingDeadlineSeconds is defined and set according to the frequency and single job duration. If it is set to 600, CronJob Controller will check missed schedules in the last 600 seconds. (read more)
Troubleshooting/Notes 🔫
Make sure you are passing the schedule properly. (check here to validate)
Use the following command to check your cronjob.
$ kubectl get cronjobs
Use the following command to check your job.
$ kubectl get pods
Cleanup
$ kubectl delete cronjob <metadata.name_of_cronjob>
Use the following command to obtain your pod’s logs.
$ kubectl get pods
$ kubectl logs — follow <POD_NAME>
Thank you for reading. Feel free to email me if you have any questions or suggestions.
Cheers! 🎉