PM2 for JavaScript (Node.js): Complete Guide with Examples
1. What Is PM2 and Why You Need It
PM2 (Process Manager 2) is a powerful process manager for Node.js applications designed for production environments. It allows you to start, stop, restart, and monitor Node.js apps, ensuring high availability and fault tolerance. PM2 automatically restarts crashed processes, distributes load across multiple application instances (clustering), provides a built-in load balancer, and supports graceful reloads with zero downtime.
In production, Node.js applications often face unexpected errors, memory leaks, or traffic spikes. PM2 solves these problems by acting as a "guardian daemon": it tracks the state of each process, logs stdout/stderr, provides performance metrics (CPU, memory), and lets you manage the app via CLI or API. Without PM2, developers would have to manually write scripts for restarting, monitoring, and scaling — PM2 automates all these tasks.
Key PM2 features include: clustering (running multiple workers across all CPU cores), zero-downtime reloads, environment management (development/production), built-in monitoring (pm2 monit), configuration file support (ecosystem.config.js), and integration with init systems (systemd, upstart) for auto-start on server boot.
2. Installation
PM2 is installed globally via npm (Node Package Manager). The exact command:
npm install -g pm2
To install a specific version:
npm install -g pm2@5.3.0
After installation, verify the version:
pm2 --version
3. Quick Start — Minimal Working Example
Create a simple Node.js application app.js:
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from PM2!\n');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Start the app with PM2:
pm2 start app.js --name my-app
Check the status:
pm2 status
Stop the app:
pm2 stop my-app
4. Core Methods/Functions/Classes
4.1. pm2.start() — Starting an Application
Signature: pm2.start(script, options, callback)
What it does: Starts the specified script as a PM2 process with given options (name, instance count, environment variables).
Working code example:
const pm2 = require('pm2');
pm2.connect((err) => {
if (err) {
console.error(err);
process.exit(2);
}
pm2.start({
script: 'app.js',
name: 'my-app',
instances: 2, // launch 2 instances
exec_mode: 'cluster', // cluster mode
env: {
NODE_ENV: 'production',
PORT: 3000
}
}, (err, apps) => {
if (err) {
console.error(err);
return pm2.disconnect();
}
console.log('App started:', apps);
pm2.disconnect();
});
});
4.2. pm2.stop() — Stopping a Process
Signature: pm2.stop(process, callback)
What it does: Stops the specified process (by name, ID, or all processes).
Working code example:
const pm2 = require('pm2');
pm2.connect((err) => {
if (err) {
console.error(err);
process.exit(2);
}
// Stop Also in library
Elasticsearch Client for Swift (iOS/macOS): Integration and Examples
Sending SMS in C# (.NET): Integration with SMS Service APIs
Working with Excel in TypeScript: Libraries, Tools, and Code Examples
Scrutor for C# (.NET): Complete Guide with Examples