How to Use PM2 for Clustering in Node.js
Use
pm2 start app.js -i max to run your Node.js app in cluster mode, where PM2 automatically creates multiple instances equal to your CPU cores. This spreads the load and improves performance by balancing requests across processes.Syntax
The basic syntax to start a Node.js app with PM2 in cluster mode is:
pm2 start <script> -i <instances>: Starts the app with the specified number of instances.<script>: Your Node.js entry file, e.g.,app.js.-i max: Automatically sets instances to the number of CPU cores.
bash
pm2 start app.js -i max
Example
This example shows how to run a simple Node.js server using PM2 in cluster mode to utilize all CPU cores.
javascript
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200); res.end(`Handled by process ${process.pid}`); }); server.listen(3000, () => { console.log(`Server running on port 3000, process ${process.pid}`); });
Output
Server running on port 3000, process 12345
Server running on port 3000, process 12346
Server running on port 3000, process 12347
Server running on port 3000, process 12348
Common Pitfalls
1. Not using cluster mode: Running pm2 start app.js without -i runs a single instance, missing clustering benefits.
2. Using too many instances: Setting instances higher than CPU cores can cause overhead and slowdowns.
3. Not handling shared resources: When clustering, avoid sharing in-memory data between instances without proper synchronization.
bash
Wrong: pm2 start app.js Right: pm2 start app.js -i max
Quick Reference
pm2 start app.js -i max: Start app with all CPU cores.pm2 list: Show running processes.pm2 stop <id|name>: Stop a process.pm2 restart <id|name>: Restart a process.pm2 logs: View logs.
Key Takeaways
Use
pm2 start app.js -i max to run your Node.js app in cluster mode using all CPU cores.Clustering improves performance by balancing load across multiple processes.
Avoid running more instances than CPU cores to prevent overhead.
Do not share in-memory data directly between clustered processes without synchronization.
Use PM2 commands like
pm2 list and pm2 logs to manage and monitor your app.