Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to containerize a NodeJS app with cron jobs using Docker?

I have a NodeJS app consisting of a REST API and an overnight maintenance (cron) job. Currently running on Debian Linux.

What is the best practice do Dockerize it?

  • I can use the official "node" Docker image, however that doesn't contain a crontab.
  • I can use the official "alpine" Docker image (and install NodeJS in it) however I lose the possibility of upgrading NodeJS with the easy of pulling a new version of the official image.

What is the best way to achieve this?

like image 635
adamsfamily Avatar asked Aug 31 '25 04:08

adamsfamily


1 Answers

Solution #1

Use a node cron package. I added some code example from a real project. Every hour I scrape a website. You can set time and place your recurring task inside cron.schedule. You can use it a separate project or combine with your api code.

import { Scraper } from './controller/scraper.js';
import cron from 'node-cron'

cron.schedule('0 0 */1 * * *', () => {
  console.log('running a task every hour');
  const scraper = new Scraper()
  const data = scraper.getData()
});

Solution #2

Docker official website doesn't advice running process managers with containers. But you can use if you need. I use pm2 as a process manager. It can be used for running an app for some intervals and it can restart your app if it crashes.

Links that will help you:

  • https://pm2.keymetrics.io/
  • https://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs/

My use case:

  • Restart app if it crashes.
  • Run app.js file for each hour.
like image 109
Hasan Gökçe Avatar answered Sep 02 '25 19:09

Hasan Gökçe