What is PM2 and Why Your Node App Needs it

Last updated: February 20th 2025

Introduction

Alright, let's talk about keeping your Node.js apps alive. I mean really alive. Because let's be honest, nothing's more frustrating than deploying your beautifully crafted application only to have it… well, just kinda stop working. Maybe it's a memory leak, maybe it's an unhandled promise rejection, maybe it’s just the internet being the internet. Whatever the reason, your app crashing is a nightmare, especially if it’s in production.

And that’s where our superhero swoops in: PM2.

Think of PM2 as your Node.js application's personal bodyguard, always on duty, making sure it’s breathing and serving requests, even when things get a little hairy. It’s more than just a process manager; it’s your production Node.js best friend. Forget forever, forget nodemon in production (please tell me you weren't doing that!), PM2 is the real deal.

So, in this little digital jaunt, we’re gonna dive deep into PM2, specifically focusing on the commands that make it so darn useful. We’ll get your Node.js apps not just running, but thriving, ready to face the internet’s glorious chaos.

Why PM2? More Than Just a Fancy Restart

Before we get command-happy, let’s quickly address why PM2 is your go-to. Sure, you could use node app.js and technically your app is "running." But what happens when it inevitably crashes? Crickets. Silence. Your users get greeted with the dreaded "This site can’t be reached." Not exactly the user experience you were aiming for, right?

PM2 steps in and solves a bunch of problems:

  • Automatic Restarts on Crash: This is the big one. PM2 monitors your app, and if it goes belly up for whatever reason, it springs into action and restarts it. No manual intervention needed at 3 AM. Sleep soundly, my friend.
  • Process Management Nirvana: Starting, stopping, restarting, deleting, listing – PM2 gives you a command for basically everything you need to do with your Node.js processes. It's your central control panel.
  • Load Balancing and Clustering (Hello Performance Boost!): Want to squeeze every ounce of performance out of your server? PM2 can help you cluster your Node.js app across multiple CPU cores, handling more requests and keeping things snappy.
  • Logging and Monitoring Out of the Box: Keeping tabs on your app is crucial. PM2 has built-in logging and monitoring features, so you can see what’s happening, troubleshoot errors, and generally keep a watchful eye.
  • Startup Script Generation (No More Manual Server Bootstrapping): Want your app to automatically start when your server reboots? PM2 can generate startup scripts for various init systems (like systemd, upstart, launchd). Set it and forget it.

Basically, PM2 takes the headache out of running Node.js apps in production. It’s like having a dedicated DevOps engineer, but, you know, in your terminal.

Getting Started: A Quick Install and the Magical start

First things first, gotta get PM2 installed. If you’ve got Node.js and npm (which, you probably do if you’re reading this), installation is a breeze:

$ sudo npm install -g pm2

Boom. You've got PM2 installed globally. Now, let's get your app running under PM2’s watchful eye. Navigate to your project directory in your terminal. Let’s say your main application file is app.js. To start it with PM2, you’d use the simplest, most fundamental command:

$ pm2 start app.js

Run that, and BAM! PM2 does its thing. You'll see some output in your terminal, something like this (it might vary slightly):

[PM2] Applying action restartProcessId on app_module id [0]
[PM2] [your-app-name] App name:app_module id:0 online
┌──────────┬────┬──────┬───────┬────────┬───────────┬──────────┬──────────┬───────────┬──────────┐
│ App nameid │ mode │ pid   │ status │ restart │ uptime   │ cpu      │ mem      │ user     │ watching │
├──────────┼────┼──────┼───────┼────────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ app_module │ 0  │ fork │ 12345 │ online │ 00s       │ 0%       │ 24.1mb   │ youruser │ disabled │
└──────────┴────┴──────┴───────┴────────┴───────────┴──────────┴──────────┴───────────┴──────────┘

Congratulations! Your app.js is now being managed by PM2. It’s running, it’s being monitored, and if it crashes, PM2 will bring it back online. Simple as pie.

Diving into the Command Buffet: Your PM2 Command Cheat Sheet

Okay, pm2 start is cool, but PM2 has a whole arsenal of commands to play with. Let's explore some of the most useful ones, broken down into categories to make it easier to digest.

1. Basic Process Control: Start, Stop, Restart, Delete

These are your bread-and-butter commands for managing the lifecycle of your applications.

  • pm2 start <script> [options]: We already covered this. Starts your script (like app.js). Options are plentiful (we'll touch on some later), letting you configure things like application name, instances, and more.

  • pm2 stop <id|name|all>: Stops a running application. You can stop by:

    • pm2 stop 0 (using the ID, like the 0 in the output above).
    • pm2 stop your-app-name (using the name you gave it – PM2 often infers a name, but you can set it explicitly).
    • pm2 stop all (stops all PM2 managed applications – be careful!).
  • pm2 restart <id|name|all>: Restarts an application. Handy after you’ve made code changes and deployed a new version. Same targeting options as stop (ID, name, all). PM2 is clever about restarts – it usually tries to do a "graceful restart" if your app supports it, minimizing downtime.

  • pm2 delete <id|name|all>: Completely removes an application from PM2’s management. Stops the process and removes it from the process list. Use this when you're done with an app and don't want PM2 to manage it anymore.

2. Monitoring and Information: List, Show, Logs, Monit

Keeping an eye on things is crucial. PM2 gives you several ways to see what’s happening under the hood.

  • pm2 list (or pm2 ls): Shows you a beautifully formatted table of all your PM2 managed processes. This is your quick overview. You see the app name, ID, status (online, errored, stopped), CPU usage, memory usage, uptime, restarts, and more. Essential for a quick health check.

  • pm2 show <id|name>: Provides detailed information about a specific application. Run pm2 show 0 (or whatever your app ID is) and prepare to be bombarded with data. Configuration, logs paths, process metrics, environment variables – it’s all there. This is your deep-dive command when you need to troubleshoot or really understand what’s going on with a particular app.

  • pm2 logs <id|name|all> [lines]: Displays the logs for your application. Super useful for debugging. pm2 logs your-app-name will stream the logs to your terminal in real-time. pm2 logs --lines 100 your-app-name will show you the last 100 lines. pm2 logs --error will show only error logs (handy for filtering).

  • pm2 monit: Opens up a simple, terminal-based monitoring dashboard. It’s a visually appealing, real-time view of your CPU, memory, and application status. Think of it as a lightweight Grafana for your terminal. Press Ctrl+C to exit.

3. Scaling and Clustering: scale

Want to leverage multi-core CPUs? pm2 scale is your friend.

  • pm2 scale <id|name> <instances>: Scales your application to run on a specified number of instances (processes). For example, if you have a 4-core CPU, pm2 scale your-app-name 4 will start four instances of your app and PM2 will automatically load balance requests across them. This is a very easy way to improve performance for Node.js apps that can benefit from horizontal scaling (most web apps can!).

  • pm2 scale <id|name> +<instances> or pm2 scale <id|name> -<instances>: Dynamically increase or decrease the number of instances. pm2 scale your-app-name +1 adds one more instance. pm2 scale your-app-name -2 removes two instances. Cool for responding to traffic spikes or dips.

4. Configuration Persistence: save and startup

Making sure your apps survive server reboots? Essential.

  • pm2 save: Saves the current list of PM2 managed processes. Think of it as creating a snapshot of your running applications. After you’ve started and configured your apps, run pm2 save.

  • pm2 startup [platform]: Generates and configures a startup script for your operating system’s init system (like systemd, upstart, launchd). After running pm2 save, run pm2 startup (you might need to specify your platform if PM2 doesn’t detect it correctly). Follow the instructions PM2 gives you (usually involves running a command as sudo). Now, when your server reboots, PM2 will automatically restart all the apps you saved. Pure magic.

Conclusion: PM2, Your Node.js App’s Best Friend in Production

So there you have it. A whirlwind tour of PM2 commands to keep your Node.js applications running smoothly, reliably, and scalably. From simple starts and stops to clustering, logging, and automatic restarts, PM2 gives you the tools you need to confidently deploy and manage your Node.js apps in production.

Stop fearing the 3 AM crash alerts. Embrace PM2, and let your Node.js apps live long and prosper. Seriously, if you're running Node.js in production and not using a process manager like PM2, you're making your life harder than it needs to be. Go install it. Go play with those commands. Your future self (and your users) will thank you.

This article was written by Ahmad AdelAhmad is a freelance writer and also a backend developer.

chat box icon
Close
combined chatbox icon

Welcome to our Chatbox

Reach out to our Support Team or chat with our AI Assistant for quick and accurate answers.
webdockThe Webdock AI Assistant is good for...
webdockChatting with Support is good for...