Can PM2 execute an npm lifecycle script?

I am trying to figure out if PM2 can handle an npm command defined in a package script instead of directly running a JavaScript file. In my development setup, I usually run a simple command, but I want to switch to a script-based approach in production. For my testing setup I normally do this:

npm run boot

When moving to production I plan to try:

pm2 start "npm run boot"

I’m also aware of a similar method using a different tool. Any advice would be really helpful.

PM2 is capable of executing npm lifecycle scripts, but there are some nuances to consider. I’ve found that wrapping your command in quotes can work, although you may need to adjust your environment variables or use an ecosystem configuration file to ensure it picks up the correct settings. In production, I usually deploy the command via PM2 by directly referencing the npm command in a custom ecosystem file. This approach provides greater control over process management and reduces potential issues with command parsing.

you can run npm scripts with pm2 but i faced some issues with quoting. using an ecosystem file sometimes smoothed things over and helped with the env settings. could try that if you hit problems, but tbh its a bit trial and error.

I have been in a similar situation and found that while PM2 can execute npm lifecycle scripts, it can be a bit finicky in production due to how it handles command parsing. I ended up switching to an ecosystem file to better manage environment variables and ensure the npm script executes properly. My ecosystem file allowed for a clearer definition of the command and made it easier to device different settings for development and production. The key point was thorough testing in the staging environment before going live, as minor tweaks in the configuration made a significant difference.

PM2 indeed has the capability to run npm lifecycle scripts, but in my experience it often requires a workaround to ensure stability. I encountered issues related to complex quoting and environment variable propagation when trying to execute the npm command directly. To overcome this, I developed a small wrapper script that calls the npm script. This approach not only simplified command handling but also provided better logging and debugging capabilities. I then used PM2 to manage the wrapper script. Testing in a staging environment was crucial in identifying and resolving any configuration discrepancies.