Getting Started with PM2, the Node.js Process Manager

Getting Started with PM2, the Node.js Process Manager

PM2, or Process Manager 2 is an incredibly versatile production process manager written in Node.js.

Uses for PM2

PM2 has a lot of uses, letís look at a few:

- Restarting after crashes: PM2 allows us to keep processes running until the heat death of the universe, or a server failure, whichever happens first

- Monitoring and managing processes remotely: A magic-powered web portal allows you to keep an eye on remote processes and manage them

- It doesnít just run Node apps: PM2 isnít limited to just Node.js processes, thatís right, you can even use it to keep your Minecraft server online

- Restart-Persistance: PM2 can remember all your processes and restart them after a system restart

- And a whole lot more

Getting started

First thing we need to do is to install PM2 globally on your machine:

$ npm i -g pm2

Basic Commands

Letís get into the basics of how to use it. To start a process under PM2, all you have to do is run pm2 start . App being the name of the file youíre running. PM2 will output something like this:

[PM2] Starting C:Usersmooseapp.js in fork_mode (1 instance)

[PM2] Done.

1. Reduced and simplified for brevity

Pay attention to what it says under id. If you forget just run pm2 list. If you want to add a name to the process when you start it, you can use the --name parameter (pm2 start app.js --name mycoolapp). Awesome! Your app is now running under PM2, if it crashes, PM2 will restart it.

2. Restarting on File Changes

Another awesome feature that PM2 has is restarting when a file in the working directory changes. To make PM2 watch our directory and restart on file changes, include the --watch flag when you start your app.

3. Persistence Through Restarts

PM2 also allows us to start our processes when our server (re)starts. Start whatever you want to have running all the time through pm2 start and then run pm2 save.

$ pm2 save

[PM2] Saving current process list...

[PM2] Successfully saved in C:Usersmoose.pm2dump.pm2

Now, when our system restarts, PM2 will start whatever processes we had running when we ran pm2 save.

How To Write and Run Your Firs …

How To Write and Run Your First Program in Node.js. Node.js is a popular open-source runtime environment that can execute JavaScript outside of the browser using the V8 JavaScript engine, which is the same engine used to power the Google Chrome web b …

read more

Test a Node RESTful API with M …

Test a Node RESTful API with Mocha and Chai. I still remember the satisfaction of being finally able to write the backend part of a bigger app in node and I am sure many of you do it too. And then? We need to make sure our app behaves the way we expe …

read more