Scale Node.js with Cluster and PM2
Use the cluster module and PM2 process manager to run multiple Node.js workers across all CPU cores for production scaling.
Prerequisites
- -Node.js installed
- -npm install -g pm2 (for PM2 usage)
Steps
Create a basic cluster setup
Use the cluster module to fork worker processes that share the same server port.
Workers share the server port via the OS kernel. Incoming connections are distributed across workers automatically.
Use PM2 for production process management
Start your application with PM2 in cluster mode for automatic worker management, logging, and restarts.
The -i max flag creates one worker per CPU core. Use -i 0 for the same effect.
Create a PM2 ecosystem configuration
Define a persistent PM2 configuration file for consistent deployments across environments.
Monitor workers with PM2
View real-time status, resource usage, and logs for all running workers.
Perform zero-downtime reload
Gracefully reload all workers one at a time to deploy new code without dropping connections.
reload restarts workers sequentially (zero-downtime). restart kills all workers at once (has downtime).
Ensure your app handles SIGINT gracefully to close connections and flush data before the worker exits.
Full Script
FAQ
Discussion
Loading comments...