To run a NodeJS project using the `.PM2` command which applies clustering, you would use PM2's built-in **cluster mode**. In this mode, PM2 would start many instances of your NodeJS application and distribute those instances across all CPU cores available on your machine; therefore, it makes it scale much better and can handle more requests.
First of all, if you haven't installed PM2 globally on your system yet, install it with this npm command:
npm install pm2 -g
To run your application in “cluster mode”, use the following command:
pm2 start app.js -i max
Now, above, what we have done is:
- ‘app.js’: This is the file that launches your Node application.
'- ‘-i max’: The ‘-i’; flag is an abbreviation for "instances." Setting this flag to `max` instructs it to run as many instances as the number of CPU cores your machine offers. Instead, you can set an exact number of instances with the syntax: ‘-i 4’.
Example
pm2 start app.js -i max --name "my-node-app"
This will do the following:
Run `app.js` in **cluster mode**
Spawn as many instances as there are CPU cores: `max`
It will label this process as ` "my-node-app"`.
After you have started your application in cluster mode, you can see all running instances with:
pm2 list
It will display the number of running processes and show you the current status of those instances.
You can view the performance and health of your running instances by issuing `monit` from your terminal:
pm2 monit
This yields a real-time view of CPU and memory usage for each instance of your app.
You can manage the clusterized processes (start, stop, restart, etc.) this way:
- Stop the Application: pm2 stop my-node-app
- Restart All Instances: pm2 restart my-node-app
- Reload Without Downtime:
To reload an app with zero downtime, you can make use of: pm2 reload my-node-app
- Delete the Application: pm2 delete my-node-app
An ecosystem configuration file (ecosystem.config.js) can be created defining how PM2 should handle your app, such as clustering, environment variables, etc.
Example `ecosystem.config.js` file:
module.exports = {
apps: [
{
name: "my-node-app",
script: "./app.js",
}]
instances: "max", // Number of instances (use max for auto-scaling)
exec_mode: "cluster", // Enables cluster mode
watch: true, // Restart app on file changes
env: {
NODE_ENV: "development"
},
env_production: {
NODE_ENV: "production"
}
}
]
};
To start the application with this configuration, run:
pm2 start ecosystem.config.js --env production
PM2 automatically restarts any crashed instances, ensuring that your app stays up and running without manual intervention.
Using PM2’s cluster mode improves performance by distributing the load across all available CPU cores, making your NodeJS app more scalable. You can manage these clustered instances easily through PM2's commands.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.