Strapi cron using pm2 cluster mode

System Information
  • Strapi Version: 3.6.0
  • Operating System: Ubuntu 18.04
  • Database: MongoDB
  • Node Version: 14.16.1
  • NPM Version: 7.9.0
  • Yarn Version: 1.22.10

Hello!

I am using pm2 to run strapi in cluster mode. The thing is that I use Strapi cron and I think that its getting duplicated due to the cluster mode.

Is there a proper way to get the strapi cron run as if it was only one instance?

Hi, I would like to use Strapi in cluster mode as well. But I don’t have a clear idea how does pm2 load balancing (cluster) works.
Whenever I run more than one instance in cluster, the logs say that the Strapi port is already in use (obviously). So do I need to specify more ports and then tell nginx to load balance?

I had this same bahaviour when I was using the ecosystem conf file. I don’t know why, but initializing directly it works. This is the command I’m using: NODE_ENV=production pm2 start server.js -i max --env production

-i max should use all available cores

Server.js content:
const strapi = require("strapi"); strapi().start();

In this case, pm2 that does the load balance thing

Sorry for reviving this, but as it ranks quite high on google for “strapi pm2 cluster”, I figured I’ll post a possible solution for running cron jobs in cluster mode.

In my project, I do this:

  const isMainCluster = parseInt(process.env.NODE_APP_INSTANCE, 10) === 0;
  if (isMainCluster || !process.env.NODE_APP_INSTANCE) {
    startCronHere();
  }

When running the project in cluster mode, each instance will have the NODE_APP_INSTANCE so in the code above I only run the cron job when it’s 0. Note that I also run the cron if the NODE_APP_INSTANCE is undefined (this is usually the case when the app is not running in a cluster). Hope this helps someone :v:

2 Likes