Perfect — let’s go through PM2, a widely used process manager for Node.js that’s essential for production deployments.
1️⃣ What is PM2?
-
PM2 = Production Process Manager for Node.js
-
Helps keep applications alive, restart on failure, and monitor performance
-
Works for single apps, clusters, or multiple apps
Key Features:
-
Process management: Start, stop, restart Node apps
-
Clustering: Run app across all CPU cores
-
Monitoring: Track CPU, memory, uptime
-
Log management: Aggregate and persist logs
-
Auto-restart: Restart apps if they crash or the server restarts
-
Zero-downtime reloads: Graceful reloads for updates
2️⃣ Installing PM2
npm install pm2 -g
3️⃣ Starting and Managing Apps
Start a Node App
pm2 start app.js --name my-app
--name
→ assign a friendly process name
List Running Processes
pm2 list
Stop / Restart App
pm2 stop my-app
pm2 restart my-app
pm2 reload my-app # zero-downtime reload
Delete App
pm2 delete my-app
4️⃣ Clustering Mode
- Utilize all CPU cores for better throughput
pm2 start app.js -i max # max = number of CPU cores
- PM2 automatically spawns multiple worker processes
5️⃣ Monitoring & Logs
Real-time Monitoring
pm2 monit
Logs
pm2 logs my-app # live logs
pm2 flush # clear logs
pm2 logs --lines 100 # last 100 lines
6️⃣ Auto Startup on Server Reboot
pm2 startup
pm2 save
- Ensures Node apps restart automatically after server reboot
7️⃣ Ecosystem File (Optional)
- Manage multiple apps with a JSON/YAML configuration file
// ecosystem.config.js
module.exports = {
apps: [
{
name: "my-app",
script: "./app.js",
instances: "max",
exec_mode: "cluster",
watch: true
}
]
};
- Start all apps:
pm2 start ecosystem.config.js
8️⃣ Key Takeaways
-
PM2 is essential for production Node.js apps
-
Provides process management, clustering, monitoring, and logging
-
Supports zero-downtime reloads for seamless deployments
-
Easily integrates with server startup scripts
Next, we could cover Node.js production best practices, combining performance, monitoring, logging, security, clustering, and deployment strategies for real-world applications.
Do you want me to go there next?