Node.js Course
Node.js
/
Intermediate

PM2

Definition

A production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, reload them without downtime, and facilitate common system admin tasks.

Explain Like I'm New

If you start your app with `node index.js` and it crashes, the server is dead until you log in and restart it. PM2 is the ultimate babysitter. You start the app with `pm2 start index.js`. If the app crashes at 3:00 AM, PM2 instantly restarts it in 1 millisecond. It also handles clustering automatically.

Real World Example

Running `pm2 start server.js -i max`. This single command tells PM2 to look at your server, see it has 8 CPU cores, clone your app 8 times, and balance the traffic between them perfectly.

Common Use Cases

  • •Production deployment
  • •Zero-downtime reloads
  • •Log management

Terminal Output

bash / terminal
// --- COMMON PM2 TERMINAL COMMANDS --- // 1. Start an app and name it 'api' // pm2 start server.js --name "api" // 2. Start it across ALL available CPU cores (Clustering) // pm2 start server.js -i max // 3. See a live dashboard of CPU and RAM usage // pm2 monit // 4. View logs // pm2 logs // 5. Zero-downtime update // pm2 reload api console.log("PM2 is the absolute industry standard for deploying Node on bare-metal servers.");

Interview Questions

basic

  • What does PM2 do if your Node application crashes?

intermediate

  • What is a 'Zero-Downtime Reload'?

Flash Cards

Question

What if it crashes?

Click to reveal answer
Answer

It automatically restarts the process instantly.

Question

What is Zero-Downtime Reload?

Click to reveal answer
Answer

When you push new code to your server, you normally have to shut it down for 5 seconds to restart it. If you have 4 clustered instances, PM2 restarts Instance 1 while 2, 3, and 4 keep serving users. It rotates through them so the server never actually goes offline during the update.