PM2 — Use NPM to Start Your App

NPM as a package manager provides a lot capabilities outside the actual dependency management. You can leverage a built-in functionality to run scripts which enables the use case of NPM as a build tool. Further, you can define a script within your package.json file that executes various tasks before finally starting your application.

This guide will show you how to use PM2 to start your application with the help of NPM.

PM2 Series Overview

Start App PM2 From Command Line

Usually when using NPM — precisely npm start — to kick off your Node.js application, you may want to run a Gulp or Grunt or any other task before ultimately starting your Node.js server. That doesn’t exclude PM2 as your process manager, because you can start your application using the pm2 command line utility and run the npm start command.

The following command starts your app and you can leverage from all the benefits that come with PM2.

pm2 start npm -- start  

Notice, that there needs to be a space after the two dashes.

The command from above adds your app as a PM2 process and you can manage it like any other. Of course, you can add further flags to the start command to customize the behavior of your app with PM2.

Start App With PM2 JSON Config File

Besides the pm2 command line utility, you can use an advanced JSON configuration to have a static configuration file that is reusable or even provides multiple app definitions. The following snippet contains only a single app with the name futurestudio-homepage which gets kicked off using NPM.

{
  "apps": [
    {
      "name": "futurestudio-homepage",
      "script": "npm",
      "args": "start"
    }
  ]
}

To simulate the npm start command within a PM2 JSON configuration, you need to pass npm as a value for the script entry point and pass the start command as the value for args. You can even further customize your JSON file with allowed options and advanced features.

Outlook

This guide walked you through the setup and usage of PM2 with NPM script commands that are used to kick off your application. You can benefit from both options provided by PM2: start your application from command line or define a JSON configuration file and ultimately run the npm start command to start and manage your server.

Please use the comments below for remarks, questions or anything that’s on your mind. Or reach out on Twitter @futurestud_io. We’re happy to read your messages :)

Make it rock & enjoy coding!

Explore the Library

Find interesting tutorials and solutions for your problems.