Tutorials > How to manage Node.js processes with PM2 on CentOS 8

How to manage Node.js processes with PM2 on CentOS 8

Published on: 09 December 2020

Development Node.js

PM2 is a process manager that can run Node.js applications as daemons within the system, restarting the applications in the event of a crash.

In this guide you will see how to install and best configure PM2. After creating a small sample application with Node.Js, you will learn how to start it, stop it, and how to properly manage its log files.

To get started, connect to your server via an SSH connection. If you haven't done so yet, following our guide is recommended to  connect securely with the SSH protocol. In case of a local server, go to the next step and open the terminal of your server.

Prerequisites

If it is not on your system, install the latest stable version of Node.Js using the following commands:

curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash -
        
yum install nodejs -y
        

Verify the installation, asking for the version installed:

node -v
v12.18.3
        

Creating an example application

To test the functionality of PM2, prepare a simple application that prints the current date on the console so that the execution of your software can be verified over time.

But first, create a directory where to save the application: then proceed using the following commands:

mkdir /var/node/pm2test -p
        

Enter the newly created directory:

cd /var/node/pm2test 
        

Using a text editor of your choice, create an "index.js" file:

nano index.js
        

Insert the following instructions into the file:

function writeToLogFile(){
        
         // Get the current date
         currentDate = (new Date()).toISOString();
                
         // Print the date
         console.log( `[${currentDate}] - Alive` );
        } 
        
        // Recall the function above every second
        setInterval( writeToLogFile , 1000 );
        

Save the file you just created and check its operation:

node index.js
[2020-09-01T10:02:15.789Z] - Alive
[2020-09-01T10:02:16.798Z] - Alive
[2020-09-01T10:02:17.800Z] - Alive
        

Stop the script from running by using the CTRL + C key combination.

PM2 installation and first start

PM2 is present as an npm package. To use it throughout the system, and not just in your application, use the "-g" parameter to perform a global installation:

npm install pm2 -g
        

Once completed, start your application using the "start" command:

pm2 start /var/node/pm2test/index.js
        

If everything works correctly, the process just started should be seen by using the command:

pm2 list
        
        ┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
        │ id  │ name     │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
        ├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
        │ 0   │ index    │ default     │ N/A     │ fork    │ 6554     │ 0s     │ 0    │ online    │ 0%       │ 25.7mb   │ root     │ disabled │
        └─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
        

Through the "list" command, PM2 allows you to view all the currently active processes, their consumption of system resources and much more information.

Then, proceed by eliminating all the processes present, using the command:

pm2 delete all      

Advanced use of PM2

To better identify the process in the PM2 list, use the -name- parameter to assign an identifier to your application.

For example, by starting the test application through:

pm2 start /var/node/pm2test/index.js --name pm2test        

You may stop it later by using the "delete" command combined with the same name -pm2test- used above:

pm2 delete pm2test
        

Through the -watch- parameter, PM2 will start the application and verify any changes in the directory. When PM2 detects changes, it will automatically restart the process.

In this case :

pm2 start /var/node/pm2test/index.js --watch
        

Another important parameter is “log”, which allows you to define where to save the output of your application, and to have more control over the file, for example by using logrotate.

By combining all the previously indicated parameters, start the application via:

pm2 start /var/node/pm2test/index.js --name pm2test --watch --log /var/log/pm2test.log        

Checking the log file via logrotate

Log files may often get too big and take up much of the disk space.

To avoid this problem, use logrotate to rotate the log file and indicate when and how the old information should be discarded.

To add a new log file, create a new file in the /etc/logrotate.d directory using a text editor:

nano /etc/logrotate.d/pm2test
        

Then, enter the following instructions and save the just created file :

/var/log/pm2test.log {
 rotate 3
 size 20M
}
        

After saving the configuration file, logrotate will periodically check the "/var/log/pm2test.log" file: if it exceeds 20 Megabytes, it will change the log name to -pm2test.log.1- to start a new one.

If the total number of saved files exceeds 3, logrotate will delete the old files to make room for the new ones.