PM2 commands for your node.js backend

11 January 2022
Essentials for deployment
node.js

PM2 is a very handy tool to keep your node.js application online. Here's a list of commands that are essential for deployment.

Commands

  1. pm2 start --name=web yarn --start or pm2 start --name=web --interpreter=bash yarn -- start

Start your application using yarn start with pm2 and assign a name web to the application. --name is useful for multiple applications in the same server. For example, backend server and web applications.

--interpreter=bash if your terminal should run with bash.


  1. pm2 delete web or pm2 delete all

Remove the process that is running the web application, if you assign a name previously. Or otherwise, delete with process id is possible as well.


  1. pm2 list or pm2 status

Show list of running processes managed by pm2.


  1. pm2 logs or pm2 logs web

Retrieve logs of running processes.


  1. pm2 flush

Remove currently logged output in log files.


Config file

If you have multiple applications to manage, it is recommended to use pm2 config file to manage the config of each application.

In parent directory:

Run pm2 ecosystem

to create a config file, Ecosystem File.

A ecosystem.config.js file will be generated.

Here's a sample config file I used for my side project.

module.exports = {
  apps: [
    {
      name: 'web',
      script: 'yarn',
      args: 'start',
      cwd: './myproject-web',
      interpreter: 'bash',
      instances: 1,
      env_production: {
        NODE_ENV: 'production',
        PORT: 3000,
      },
    },
    {
      name: 'api',
      script: 'yarn',
      args: 'start',
      cwd: './myproject-backend',
      interpreter: 'bash',
      instances: 1,
      env_production: {
        NODE_ENV: 'production',
        PORT: 5000,
      },
    }
  ],
};

That's all! Hope it helps.

Cheers.