Using pm2 to Manage Node.js Applications

Using pm2 to Manage Node.js Applications

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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...