Skip to main content

Node.js deployment with pm2

For running Node.js applications in production, you need process manager who takes care of the node processes.

We explain how to use the PM2 for setting up a Node.js Application for production on this site.

PM2

PM2 is a daemon process manager that will help you manage and keep your application online.

Installation

  1. Log in via SSH with your Site User:
ssh john-doe@instance-ip-address
  1. Go to the root directory of your project:
cd htdocs/www.domain.com/
  1. Install the latest pm2 via npm.
npm install pm2@latest -g

Start the Application

Use the following command to start your application via pm2:

App Name

Replace the app-name variable with the name of your application.

pm2 start npm --name $app-name -- start

Your application is now running via pm2.

PM2 Start NPM

Save Configuration

To save the pm2 configuration, execute the save command:

pm2 save

Adding a Cron Job

To ensure, that your application is running after a reboot of your instance, you need to configure a cron job.

  1. First copy the output of the PATH variable:
echo $PATH

The output will look similar to this:

/home/john-doe/.nvm/versions/node/v14.19.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  1. Edit the crontab for the site user.
crontab -e
  1. Add the following lines to it:
PATH=$PASTE_THE_OUTPUT_OF_$PATH
@reboot pm2 resurrect &> /dev/null

Example configuration

PM2 Cronjob Example
  1. Reboot your instance and check if the application is running:
pm2 status

The status should be online to confirm that your Application is running after reboot.

PM2 Cronjob Example

Troubleshooting

PM2 provides a logs command to see the application's output, which helps troubleshoot.

pm2 logs