How to Install PM2 in Ubuntu 22.04?

03-Apr-2023

.

Admin

How to Install PM2 in Ubuntu 22.04?

Hello Friends,

This tutorial will provide an example of how to set up a node.js application for production on ubuntu 22.04. This article will give a simple example of installing node.js and pm2 in ubuntu 20.04. We will use how to install pm2 on ubuntu 20.04. Here you will learn how to deploy node.js applications with pm2 on ubuntu.

Install and Configure PM2 in Ubuntu 22.04, follow this tutorial.

Note: "PM2" should be capitalized as it is an acronym.

Step 1: Install PM2 Using NPM


Execute the following command on terminal to install PM2 via the NPM package manager:

npm install pm2 -g

Step 2: Build Node.js App

Create a new file named app.js in your favorite text editor.

Paste the following contents 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}/`);

});

Exit and save the file.

Step 3: Start Node JS Application Using PM2

Execute the following command on the terminal to start a Node.js application with PM2:

pm2 start app.js

Note that:- we may use several additional parameters when starting an application:

  • --name <app_name> – specify an application name
  • --watch – restart your application automatically when a file changes
  • --max-memory--restart <100MB> – a memory limit that triggers an automatic restart when reached
  • --log <log_file> – specify a log file
  • -- arg1 arg2 – pass extra arguments to the script
  • --restart-delay <2000ms> – delay between automatic restarts in milliseconds
  • --time – prefix logs with time
  • --no-autorestart – turn off automatic application restarts
  • --cron – a cron job pattern for automatic application restarts
  • --no-daemon – do not run the application in a daemon process
  • Visit the official documentation to view all available parameters.

    Step 4: Manage the Application

    Let’s use the following commands on the terminal to restart, reload, stop, and delete operations in the node js app with pm2.

    To restart the application.

    pm2 restart app

    To reload an application.

    pm2 reload app

    To stop an application.

    pm2 stop app

    To delete an application.

    pm2 delete app

    I hope it can help you...

    #Ubuntu