Using pm2 to Manage Node.js Applications

Using pm2 to Manage Node.js Applications

Daily short news for you
  • After waking up, I saw everyone buzzing about the Reasoning R1 model from Deepseek.

    Wow, what's all the hype about? There's a lot! First of all, it's open-source, then there's its performance, which is on par with OpenAI's o1, and thirdly, there are multiple parameter options from 1.5B to 70B to choose from or research.

    » Read more
  • Lets go hot 🔥🔥🔥

    A really great and detailed guide about jj - Jujutsu - as I shared earlier jujutsu-tutorial

    » Read more
  • Every time I create a new website, what is the first thing that gives you the biggest headache? For me, it’s definitely the layout. Within the layout, there is one aspect that has a very profound impact, which is the font. Indeed, a website becomes much more elegant depending heavily on the font. The combination of multiple fonts together, placed correctly, and visually pleasing to users will leave a very deep impression.

    However, choosing fonts has never been easy; I just discovered the site uifonts.app that helps everyone quickly check whether this font fits their new website idea or not 😇

    » Read more

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

After that, you can start your Node application:

$ pm2 start app.js

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

$ pm2 list

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

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

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

To restart after stopping:

$ pm2 start 0

Or to restart:

$ pm2 restart 0

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

$ pm2 delete 0

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'
  }]
}

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

$ pm2 start ecosystem.config.js

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

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

$ pm2 save

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);

Run it:

$ pm2 start rpc.js

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

$ pm2 trigger rpc countActive

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.

pm2 plus

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!

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...
Scroll or click to go to the next page