Using pm2 to Manage Node.js Applications

Using pm2 to Manage Node.js Applications

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » 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...