PM2 (Process Manager 2) is a popular process manager for Node.js applications, allowing developers to manage and keep their applications online. One common requirement when using PM2 is to run npm scripts, such as npm start
, which are defined in the application’s package.json
file.
By default, PM2 allows you to run JavaScript files directly, but running npm scripts requires a slightly different approach. Fortunately, PM2 provides several ways to accomplish this.
Running npm Scripts Directly
To run an npm script using PM2, you can use the following command:
pm2 start npm -- start
This will execute the start
script defined in your application’s package.json
file. You can replace start
with any other script name defined in your package.json
file.
To assign a name to the PM2 process, you can use the --name
option:
pm2 start npm --name "app-name" -- start
This will allow you to easily identify and manage your application’s process using PM2.
Using a Configuration File
Another way to run npm scripts with PM2 is by using a configuration file, typically in JSON format. This approach allows you to define multiple applications and their corresponding scripts in a single file.
Here’s an example of a pm2.json
file:
{
"apps": [
{
"name": "my-app",
"script": "npm",
"args": "start"
}
]
}
In this example, the script
property is set to npm
, and the args
property is set to start
. This tells PM2 to run the start
script using npm.
To start your application using this configuration file, simply run:
pm2 start pm2.json
You can also specify a different working directory for your application by adding a cwd
property to the configuration file. For example:
{
"apps": [
{
"name": "my-nested-app",
"cwd": "./nested-app",
"script": "npm",
"args": "start"
}
]
}
This will tell PM2 to change into the ./nested-app
directory before running the start
script.
Running Specific npm Scripts
If you have multiple scripts defined in your package.json
file, you can run a specific script using PM2 by modifying the command:
pm2 start npm --name "app-name" -- run "script-name"
Replace script-name
with the actual name of the script you want to run.
For example, if you have a script named start:production
in your package.json
file, you can run it using:
pm2 start npm --name "my-app" -- run "start:production"
This will execute the start:production
script defined in your application’s package.json
file.
Conclusion
In this tutorial, we’ve covered how to run npm scripts with PM2. By using the techniques outlined above, you can easily manage and keep your Node.js applications online using PM2. Whether you’re running a simple npm start
script or a more complex deployment process, PM2 provides the flexibility and features you need to succeed.