What is PM2?
PM2 (Process Manager 2) is a powerful process manager for Node.js applications. It not only starts and restarts applications but also provides built-in tools for performance monitoring, cluster management, and real-time metric collection.
Why do you need PM2?
When deploying production Node.js applications, several challenges arise: automatic restart on failure, load balancing across CPU cores, viewing logs, and tracking memory/CPU usage. PM2 solves all these tasks out of the box, replacing several tools (nodemon, forever, cluster).
Installation
npm install -g pm2Global installation allows you to run PM2 from anywhere on the system.
Main Monitoring Features
- pm2 list — displays all running processes with PID, status, memory and CPU usage.
- pm2 monit — an interactive terminal monitor showing real-time metrics for each process.
- pm2 show <id> — detailed information about a specific process: uptime, restart count, Node.js version, environment variables.
- pm2 logs — view combined logs of all applications or a specific process.
- pm2 status — brief status of all applications.
Code Example (Node.js)
Create a file app.js:
const http = require('http');const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello from monitored app!');});server.listen(3000, () => { console.log('Server running on port 3000');});Run with monitoring:
pm2 start app.js --name my-app --watchpm2 monitThe --watch flag automatically restarts the application when files change. The pm2 monit command opens a panel where you can see CPU load, memory, request count, and uptime.
When to Use
PM2 is ideal for production environments: web servers (Express, Koa), API services, bots, microservices. It is indispensable when you need to:
- Ensure 24/7 application uptime
- Automatically restart after a crash
- Scale the application across all CPU cores
- Collect metrics for further analysis
- Centrally manage logs
PM2 is not suitable for one-off scripts or local development (nodemon is better for that).
Conclusion
PM2 is the de facto standard for monitoring Node.js applications. It is easy to install, provides a rich set of metrics, and integrates easily with alerting systems (via plugins). Start with pm2 monit to see the health of your application in real time.