How To Deploy Node.js App on Ubuntu with PM2

Deploy Node.js App on Ubuntu with PM2

PM2 is an advanced, production process manager for Node.js applications. In this tutorial, you will learn how to deploy your Node.js applications on a production server using the pm2 tool. PM2 helps you monitor applications, their memory and CPU uses. Also, provide easy commands to stop/start/restart all apps or individual apps.

Step 1 – Install Node.js

First, you need to node.js PPA in our system provides by the nodejs official website. We also need to install the python-software-properties package if not installed already.

sudo apt install python-software-properties
curl -sL | sudo -E bash -

After adding required PPA file lets install Nodejs package. NPM will also be installed with node.js. This command will also install many other dependent packages on your system.

sudo apt install nodejs

Step 2 – Install PM2

Now, Use npm to install process manager for Node.js using the following command. This will install the latest version of pm2 on your system.

sudo npm install pm2@latest -g

Step 3 – Start Application with PM2

Now create PM2 configuration file. For this tutorial, I have two Node.js applications to host on the production server. The source code applications are available under /var/www/parse-apps/app1 and /var/www/parse-apps/app2 directories. Create a configuration file parse-apps.config.js with the following content. My both applications have index.js startup JavaScript file to run my application.

module.exports = {
  apps : [{
    name        : "My App 1",
    script      : "index.js",
    watch       : true,
    merge_logs  : true,
    cwd         : "/var/www/parse-apps/app1/",
    name        : "My App 2",
    script      : "index.js",
    watch       : true,
    merge_logs  : true,
    cwd         : "/var/www/parse-apps/app2/",

Now use following command to start application with pm2. In below command we are passing parse-apps.config.js configuration file name. PM2 will read configuration file and start all applications and assign a uniq id.

pm2 start parse-apps.config.js


Step 4 – Manage Processes with PM2

To list all processes registered under PM2 using following command. This will also display the status of the application, process id, and other useful information.

sudo pm2 list

To view more details of the specific process, you can use below command followed by id or process app name.

sudo pm2 show 1

You can also monitor all processes CPU and memory uses in real-time.

sudo pm2 monit