Run a Node.js Application in PM2 Cluster Mode for Better Performance and Fault Tolerance
Learn how to launch a Node.js app with PM2’s cluster mode to utilize all CPU cores, gain automatic restarts, and improve fault tolerance.
07 Aug 2025, 21:16 UTC

Desired outcome
Start a Node.js application with PM2 in cluster mode so that multiple worker processes share the workload, use all available CPU cores, and are automatically restarted if they crash.
Prerequisites
- Node.js (v14 or later) installed.
- PM2 installed globally (
npm install -g pm2). - Application code that is stateless or relies on an external store (e.g., Redis, database) for session data.
- Basic familiarity with running a Node.js app via
node app.js.
Procedure
- Navigate to your project directory
cd /path/to/your-node-app - Start the app in cluster mode
Use the
-iflag to specify the number of instances.maxtells PM2 to fork one worker per CPU core.pm2 start app.js -i max --name my-appReplace
app.jswith your entry file. The--nameoption gives the process set a friendly identifier. - Optional: Declare instances in an ecosystem file
Create
ecosystem.config.js:module.exports = { apps : [{ name : 'my-app', script : 'app.js', instances : 'max', exec_mode : 'cluster' }] };Then start with:
pm2 start ecosystem.config.js
Expected checks
- Verify instance count
pm2 listThe
Onlinecolumn should show the number of workers you requested (e.g., 4 on a quad‑core machine). - Monitor resource usage
pm2 monitWatch CPU and memory per worker; look for any process that repeatedly exits and restarts.
- Inspect logs
pm2 logs my-app --lines 50Ensure there are no error spikes shortly after startup. Logs from all workers are aggregated; you can view a specific worker with
pm2 show <id>.
Recovery options
- Automatic restart
If a worker crashes, PM2 will respawn it to maintain the desired instance count.
- Manual scaling
Increase or decrease workers without downtime:
pm2 scale my-app 6 # scale to six instances pm2 scale my-app 2 # scale back to two - Stop and delete
To revert the changes made by starting the app:
pm2 stop my-app pm2 delete my-appThis removes the process set from PM2’s process list.
- The application must externalize any in‑memory state (e.g., session caches) to a shared store; otherwise each worker will have its own copy, leading to inconsistent behavior.
- Memory usage roughly scales with the number of workers; ensure sufficient RAM to avoid swapping.
- Verify that libraries you use are cluster‑aware or do not rely on single‑process globals.
Limitations and practical verification
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.