DEV Community

Cover image for Using pm2 to Manage Node.js Applications
Hoai Tong Xuan
Hoai Tong Xuan

Posted on • Originally published at 2coffee.dev

Using pm2 to Manage Node.js Applications

The Problem

When I first encountered Node.js and also learned how to use Linux, nodemon was a library that I often used to develop applications, as it would automatically "reload" the new code upon saving without needing to manually "kill" and restart the application, a feature now commonly referred to as "hot reload."

After development comes deployment. While practicing running the application on the server, I struggled to figure out how to run it. If I used the conventional method of typing "node index.js" or even used nodemon, whenever I exited the terminal or disconnected from the server, the application would also "disappear." I understood that the application would exit if the connection to the server was lost. So what to do?

It was only later that I learned that to keep the application running continuously, we need a process management tool. This is not only necessary for Node but for most other languages as well. For Node, the most mentioned name is probably pm2.

Since I discovered pm2, I have been able to easily deploy my applications. However, over time, as I worked on many projects and encountered other technologies like Docker, Kubernetes, etc., pm2 gradually became less essential, as those tools already integrated management capabilities.

Recently, while maintaining several projects, most of which used pm2, I had to spend time revisiting the documentation on how to use it, as it had been a while since I last used it. At that time, I suddenly realized that there had been many changes during that period. Many new features had been added, or there were features that I was not aware of.

But I must honestly say that pm2 is still a very powerful Node.js application management tool. Anyone working with Node should take the time to learn about it. Therefore, in today's article, I will highlight some of the main features of this tool.

What is PM2?

pm2 is a daemon process manager that helps you manage and keep your applications always online.

Installing pm2 is very simple, through npm which is integrated with Node.

$ npm install pm2@latest -g
Enter fullscreen mode Exit fullscreen mode

After that, you can start your Node application:

$ pm2 start app.js
Enter fullscreen mode Exit fullscreen mode

The application runs in the background, and to see all running applications:

$ pm2 list
Enter fullscreen mode Exit fullscreen mode

The most useful feature of pm2 is that it keeps the application running in the background, meaning that even if you exit the server, your application will still run.

Most people know that when running a Node application, it only runs on one core of the CPU. If the computer is multi-core, Cluster mode will help distribute all processes to the remaining cores. For example, if the CPU has 4 cores and you want to run on all 4, it's very simple.

$ pm2 start app.js -i max
Enter fullscreen mode Exit fullscreen mode

max indicates all cores will participate; if you want a specific number, replace max with a number.

pm2 has a logging mechanism that writes logs to files for later retrieval. This information includes commands printed to the console like console.log. To view the logs:

$ pm2 logs 0
Enter fullscreen mode Exit fullscreen mode

Where 0 is the id of the process, or you can replace it with the name of the process.

To stop a process:

$ pm2 stop 0
Enter fullscreen mode Exit fullscreen mode

To restart after stopping:

$ pm2 start 0
Enter fullscreen mode Exit fullscreen mode

Or to restart:

$ pm2 restart 0
Enter fullscreen mode Exit fullscreen mode

Or to completely delete the application, ensuring it was stopped beforehand:

$ pm2 delete 0
Enter fullscreen mode Exit fullscreen mode

The pm2 start commands are discrete and singular. Imagine if instead of one, there were multiple Node processes that needed to start at the same time? That's when ecosystem becomes useful. The ecosystem is a mechanism that groups all applications into a configuration file and starts them with a single command.

To create a configuration file, use the command pm2 ecosystem, which generates a file ecosystem.config.js like the following:

module.exports = {
  apps : [{
    name: "app",
    script: "./app.js",
    env: {
      NODE_ENV: "development",
    },
    env_production: {
      NODE_ENV: "production",
    }
  }, {
     name: 'worker',
     script: 'worker.js'
  }]
}
Enter fullscreen mode Exit fullscreen mode

Adjust the configuration to fit your project and start it using:

$ pm2 start ecosystem.config.js
Enter fullscreen mode Exit fullscreen mode

In the event of a server restart, pm2 does not automatically start, causing all applications to become inactive. To address this issue, use the command:

$ pm2 startup
Enter fullscreen mode Exit fullscreen mode

But before that, you need to "commit" the processes to be started at startup with the command:

$ pm2 save
Enter fullscreen mode Exit fullscreen mode

pm2 save creates a "snapshot" of the currently running processes to restore them later.

Advanced PM2

Pm2 has some relatively useful advanced features in certain cases.

RPC Function works by running a function via the command line. For example, there is a function countActive that returns the number of people currently online.

First, create a file rpc.js with the content:

const tx2 = require('tx2');

tx2.action('countActive', (reply) => {
  const num = UserModel.count();
  reply({ num: num });
})

setInterval(function() {
  // Keep application online
}, 100);
Enter fullscreen mode Exit fullscreen mode

Run it:

$ pm2 start rpc.js
Enter fullscreen mode Exit fullscreen mode

Then, if you want to trigger the countActive function, simply use:

$ pm2 trigger rpc countActive
Enter fullscreen mode Exit fullscreen mode

Pm2 also provides an API to manage pm2 via RESTFul API. Simply put, this means you can create a server to add/edit/delete other applications using pm2, done through calling the API. You can read more details at PM2 API.

And a few other advanced features as well.

Recently, pm2 has also launched the pm2 plus service, which allows comprehensive monitoring of applications such as real-time monitoring interface, reporting, logging, and notifications... It can be seen that it is quite similar to APM (Application Performance Monitoring) applications. However, since there is no free package, I haven't had the chance to experience this service. If you have or are using it, please leave a comment at the bottom of the article!

Top comments (0)