How to Install PM2 in Ubuntu 22.04

Step 1 : Install PM2 Using NPM

Use the NPM package manager to install PM2 by entering the following command in the terminal:

npm install pm2 -g

Step 2 : Generate a PM2 Start Script for the Init System:

PM2 is designed to operate with the default init system on a Linux system (which it can automatically detect) to produce the startup script and set up PM2 as a service that can then be restarted at system boot. Simply execute the following command as root to generate the startup script:

pm2 startup

 Step 3 : Build Node.js App

Create a new file with the name app.js in your chosen text editor. Copy and paste the following command into the file:

const http = require('http');
 
const hostname = '0.0.0.0';
const port = 80;
 
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World');
});
 
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Save the file and exit.

Step 3 : Start Node JS Application Using PM2

Run the following command in the terminal to launch a Node JS application using PM2:

pm2 start app.js

Keep in mind that when we start an application, we may also use the following extra parameters:

  • Specify a name for the application: --name <app_name>
  • When a file changes, your application will start itself again automatically: --watch
  • An automated restart upon reaching a memory limit: --max-memory--restart <100MB>
  • Specify a file for the log: --log <log_file>
  • Pass added arguments to the script: -- arg1 arg2
  • Delay before automatic restarts in milliseconds: --restart-delay <2000ms>
  • Prefix logs with time --time
  • Disabling the application to restart automatically: --no-autorestart
  • A cron job pattern for an automatic restart of the application: --cron
  • Disabling the application to run in a daemon process: --no-daemon

Go visit the official documentation to see all available parameters.

Step 4 : Manage the Application

Let's use the following commands in the terminal to restart, reload, stop, and delete operational processes in the Node JS application using PM2:

  • The application will restart:
pm2 restart app

  • The application will reload:
pm2 reload app

  • The application will stop:
pm2 stop app

  • The application will delete:
pm2 delete app

Conclusion

The tutorial allows anyone to quickly and effectively learn the processes of the installation and configuration of PM2 on Ubuntu 22.04.