PM2 process management for Node.js - Mastering PM2 Process Management...
Source: Dev.to
Why You Need PM2 for Node.js Apps
Running a Node.js server directly with node app.js is fine for development, but it isn’t ready for production. If your app crashes, it stays down. PM2 is a production process manager that keeps your apps alive forever.
Key benefits
- Automatic Restarts – PM2 restarts a crashed app instantly, reducing downtime.
- Load Balancing – Run multiple instances to use all CPU cores and handle more traffic.
- Zero‑Downtime Reloads – Update code without stopping the app; PM2 gracefully reloads it.
- Monitoring – Simple CLI commands let you view logs and resource usage.
- Simple Setup – Get started in minutes.
- Ecosystem Management – Manage multiple Node.js apps from a single place, ideal for microservices.
Getting Started with PM2 Process Management for Node.js
Prerequisite: Node.js must be installed. Learn more about Node.js on Wikipedia.
Install PM2 Globally
npm install pm2 -g
Start Your App
pm2 start app.js
Replace app.js with your entry file. PM2 will daemonize the process and keep it running.
Name Your App (Optional but Recommended)
pm2 start app.js --name my-awesome-app
You can then refer to the app by its name.
Run Multiple Instances (Clustering)
pm2 start app.js -i max
The -i max flag tells PM2 to launch as many instances as there are CPU cores.
Save the Process List
pm2 save
This stores the current process list so PM2 can resurrect the apps after a reboot.
Configure Startup Script
pm2 startup
Follow the printed instructions to generate a system‑specific startup script. See the full guide in the PM2 docs.
Best Practices for PM2 Process Management for Node.js
Use an Ecosystem File
Instead of long CLI arguments, define your apps in an ecosystem.config.js (or JSON/YAML) file.
module.exports = {
apps: [
{
name: "my-awesome-app",
script: "./app.js",
instances: "max",
exec_mode: "cluster",
watch: false,
env: {
NODE_ENV: "production"
}
}
]
};
Create a starter file with pm2 init.
Monitor Your Apps
- Real‑time dashboard:
pm2 monit - View logs:
pm2 logs(filter by app name if needed)
Handle Logs Properly
- Rotate logs with tools like
logrotate. - Output JSON logs for easier parsing:
pm2 logs --json.
Graceful Shutdowns
Ensure your Node.js code listens for termination signals:
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
function gracefulShutdown() {
// close DB connections, finish pending work, then exit
process.exit(0);
}
PM2 sends these signals when restarting or stopping an app.
Keep PM2 Updated
npm update pm2 -g
Regular updates bring new features and bug fixes, improving stability.
Summary and Next Steps
PM2 provides essential stability, scalability, and management features for production Node.js applications. You now know how to:
- Install PM2 globally.
- Start and name your apps.
- Use clustering for load balancing.
- Save process lists and configure startup scripts.
- Apply best‑practice patterns such as ecosystem files, monitoring, log rotation, graceful shutdowns, and regular updates.
Explore more advanced capabilities on the official PM2 website. Consistent uptime builds user trust and lets you focus on delivering features rather than firefighting crashes.
Frequently Asked Questions
Why is PM2 essential for Node.js applications in production?
PM2 automatically restarts crashed processes, balances load across CPU cores, provides monitoring and log management, and can resurrect apps after system reboots—key factors for maintaining uptime and performance.
How do I get started with PM2 process management for Node.js?
- Install globally:
npm install pm2 -g. - Start your app:
pm2 start app.js. - Use
pm2 saveandpm2 startupto ensure persistence across reboots.
What are some best practices for managing Node.js applications with PM2?
- Use an ecosystem file for consistent configuration.
- Run in cluster mode (
-i max) to leverage all CPU cores. - Implement graceful shutdown handling in your code.
- Rotate and centralize logs.
- Regularly update PM2 and monitor apps via
pm2 monitandpm2 logs.