Can pm2 run an 'npm start' script
Asked Answered
T

23

427

Is there a way for pm2 to run an npm start script or do you just have to run pm2 start app.js

So in development

npm start

Then in production with pm2 you would run something like

pm2 start 'npm start'

There is an equivalent way to do this in forever:

forever start -c "npm start" ./
Tamper answered 23/7, 2015 at 6:18 Comment(1)
This is extension to Answer given by Dhaval https://mcmap.net/q/80801/-can-pm2-run-an-39-npm-start-39-script 1. First add pm2 to your package.json 2. For development mode, update your package json script like this: "pm2:dev": "node_modules/pm2/bin/pm2-dev start npm -- start",Whited
S
861

PM2 now supports npm start:

pm2 start npm -- start

To assign a name to the PM2 process, use the --name option:

pm2 start npm --name "app name" -- start
Supplicant answered 12/6, 2016 at 14:23 Comment(15)
How can you set a name for the process when using this command? I tried using --name "app" but it just set it to npm.Multi
pm2 start npm --name "Your APP Name" -- startPoltroon
Anyone know how to set npm start in the process file?Cumuliform
How comes I got "stopped" status when I try this? my start script looks like this "start": "cross-env NODE_ENV=production nodemon dist-prod/server.js"Steward
What does the double dash do in this command? I was trying to look it up in the docs and in the cli --help readout for pm2 but couldn't find the explanation.Weird
ah, I think I found the answer to my question. It's not a pm2 or npm thing, it seems to be a *nix way of saying "I'm done giving command options and want to start passing arguments": unix.stackexchange.com/questions/11376/…Weird
In theory, could npm be substituted for any other node-based bin module installed globally, and passed whatever arguments that module needs after ` -- ` the same way?Upbear
For me it throws an error in the logs: C:\DEV\NODEJS\NPM.CMD:1 0|weally | (function (exports, require, module, __filename, __dirname) { :: Created by npm, please don't edit manually. 0|weally | ^ 0|weally | 0|weally | SyntaxError: Unexpected token : 0|weally | at new Script (vm.js:74:7) similar issue here: github.com/Unitech/pm2/issues/3652Harrold
You can also use it as pm2 start --name "App Name" npm -- startDenna
it didn't work in my case. Initially it ran but when I ran pm2 list, I got the status 'stopped'Anastasio
-- signifies the end of a command. So npm is the actual command and start is the args here.Monroemonroy
To run PM2 with npm start method and to give it a name pm2 start npm --name "your_app_name" -- startDehypnotize
the two slashes what exactly are doing?Sling
@laukik-patel , What is the meaning of the two dashes " -- " in "pm2 npm -- start"?Traditional
I'm never gonna remember how to put these -- two times... I keep coming to this answer for years now.Hirschfeld
A
175

Those who are using a configuration script like a .json file to run the pm2 process can use npm start or any other script like this -

my-app-pm2.json

{
    "apps": [
        {
            "name": "my-app",
            "script": "npm",
            "args" : "start"
        }
    ]
}

Then simply -

pm2 start my-app-pm2.json

Edit - To handle the use case when you have this configuration script in a parent directory and want to launch an app in the sub-directory then use the cwd attribute.

Assuming our app is in the sub-directory nested-app relative to this configuration file then -

{
    "apps": [
        {
            "name": "my-nested-app",
            "cwd": "./nested-app",
            "script": "npm",
            "args": "start"
        }
    ]
}

More detail here.

Amata answered 6/3, 2017 at 7:6 Comment(8)
how does this work if I want to run the start npm script from a parent folder?Melvamelvena
Could you elaborate a bit more? I assume you're asking How to run npm start from outside the project directory? .Amata
I'm using the configuration script to run multiple node apps that are in sub-folders. The package.json with the start script information is in one of them. See this gist: gist.github.com/gianpaj/04c5680a8275616aac5e46374e07f673 When I run this it doesn't know where npm should run from. ThxMelvamelvena
@GianfrancoP. You can use the cwd attribute. Check my edited answer :)Amata
I tried to use sudo npm and it shows access error to create a directory tough I have given all the permission to user as root and also running pm2 command as sudo pm2 start config.jsonMerline
How to start multi npm start with pm2? when I add call this another one will display errorLimit
How can i run something like npm run server or npm run proxy? Would change args with server be enough?Hydrophilic
I had serious issues getting this working, getting all kinds of /usr/bin/bash: start: No such file or directory and similar errors. The solution was to pm2 delete the service and start again. Apparently you can get the "instance" stuck somehow and no amount of config edit will save it.Kindergartner
C
93

To use npm run

pm2 start npm --name "{app_name}" -- run {script_name}

Crandall answered 19/12, 2018 at 14:22 Comment(1)
Indeed, I agree with @Adiii , given that it can be run as an npm script, it just doesn't get any better than that!Wooldridge
P
58

I needed to run a specific npm script on my app in pm2 (for each env) In my case, it was when I created a staging/test service

The command that worked for me (the args must be forwarded that way):

pm2 start npm --name "my-app-name" -- run "npm:script"

examples:

pm2 start npm --name "myApp" -- run "start:test"

pm2 start npm --name "myApp" -- run "start:staging"

pm2 start npm --name "myApp" -- run "start:production"

Hope it helped

Priming answered 9/3, 2020 at 8:27 Comment(1)
notice that there is a space in between "-- run". Space needs to be there else you will get invalid option run.Clubhaul
M
52

Yes. Use pm2 start npm --no-automation --name {app name} -- run {script name}. It works. The --no-automation flag is there because without it PM2 will not restart your app when it crashes.

Mittel answered 3/3, 2016 at 5:43 Comment(3)
Do you have any idea how to use this flag inside of the ecosystem.js configuration file?Override
UPDATE: Okay I found it you need to specify "automation": false.Override
@twigg pm2 --help | grep 'no-autom' returns one line for me in version 1.0.2Mittel
M
46

you need to provide app name here like myapp

pm2 start npm --name {appName} -- run {script name}

you can check it by

pm2 list

you can also add time

pm2 restart "id" --log-date-format 'DD-MM HH:mm:ss.SSS'

or

pm2 restart "id" --time

you can check logs by

pm2 log "id"

or

pm2 log "appName"

to get logs for all app

pm2 logs
Medley answered 20/2, 2020 at 9:51 Comment(2)
Hi, @pharaj_ali, can you explain this part -- run {script name} ? I can't found it on the pm2 documentation. I've read on the edit history of your answer and I've found this interesting edit: in case of different script name use run with script name and in case of start script no need to add run. If I understand, using run {script name} is for multiple script and with only npm start it's more relevant to use pm2 start npm --name {appName} -- start? Plus I don't understand why the space between --and start/run any suggestions? ThanksNavigator
Hi @YohanW.Dunon yes you are right while running npm, if we are using start script then we don't need to use run there npm start but in case of other script we use run like npm run {script name} for the case of space between --, I think it is simply the way they use (not sure) let me know if you find answer for thatMedley
U
37

I wrote shell script below (named start.sh). Because my package.json has prestart option. So I want to run npm start.

#!/bin/bash
cd /path/to/project
npm start

Then, start start.sh by pm2.

pm2 start start.sh --name appNameYouLike
Utricle answered 1/9, 2015 at 0:17 Comment(2)
That's nice. Unfortunately this doesn't work when using the startOrRestart command.Tiber
@Tiber just use the -f flag at the end. It forces a start. (i.e it'll restart if already started)Mcadams
C
20

Yes we can, now pm2 support npm start, --name to species app name.

pm2 start npm --name "app" -- start
Caporetto answered 29/9, 2018 at 7:19 Comment(1)
This is the answer which really helped me. Thanks a lot.Dichromate
O
17

You can change directory to your project

cd /my-project

then run

pm2 start "npm run start" \\ run npm script from your package.json

or

pm2 start "yarn start"

read more here

Oleander answered 29/1, 2022 at 14:21 Comment(0)
C
14

See to enable clustering:

pm2 start npm --name "AppName" -i 0 -- run start

What do you think?

Credo answered 30/6, 2016 at 16:27 Comment(2)
what does the -i 0 do?Helman
Start maximum processes depending on available CPUs (cluster mode)Credo
V
12

If you use PM2 via node modules instead of globally, you'll need to set interpreter: 'none' in order for the above solutions to work. Related docs here.

In ecosystem.config.js:

  apps: [
    {
      name: 'myApp',
      script: 'yarn',
      args: 'start',
      interpreter: 'none',
    },
  ],
Vogele answered 31/10, 2019 at 17:10 Comment(0)
A
10

pm2 start npm --name "custom_pm2_name" -- run prod

"scripts": {
    "prod": "nodemon --exec babel-node ./src/index.js"
  }

This worked for me when the others didnt

Archon answered 10/12, 2019 at 3:1 Comment(1)
Thank you so much, Luke. Especially appreciate that you posted your script alongside, no more guessing which "start" is which :) This should be rated higher, finally something that just works.Mantelpiece
C
10

For the normal user

PM2 now supports npm start:

pm2 start npm -- start

To assign a name to the PM2 process, use the "--name" option:

pm2 start npm --name "your desired app name" -- start

For the root user

sudo pm2 start npm -- start

To assign a name to the PM2 process, use the "--name" option:

sudo pm2 start npm --name "your desired app name" -- start
Chouest answered 22/4, 2021 at 12:21 Comment(0)
S
8

Yes, Absolutely you can do it very efficiently by using a pm2 config (json) file with elegance.

package.json file (containing below example scripts)

"scripts": {
    "start": "concurrently npm:server npm:dev",
    "dev": "react-scripts start",
    "build": "node ./scripts/build.js",
    "eject": "react-scripts eject",
    "lint": "eslint src server",
    "shivkumarscript": "ts-node -T -P server/tsconfig.json server/index.ts"
  }

Suppose we want to run the script named as 'shivkumarscript' with pm2 utility. So, our pm2 config file should be like below, containing 'script' key with value as 'npm' and 'args' key with value as 'run '. Script name is 'shivkumarscript' in our case.

ecosystem.config.json file

module.exports = {
    apps: [
        {
            name: "NodeServer",
            script: "npm",
            automation: false,
            args: "run shivkumarscript",
            env: {
                NODE_ENV: "development"
            },
            env_production: {
                NODE_ENV: "production"
            }
        }
    ]
}

Assuming that you have already installed Node.js, NPM and PM2 on your machine. Then below should be the command to start the application through pm2 which will in turn run the npm script (command line mentioned in your application's package.json file):

For production environment:

pm2 start ecosystem.config.js --env production --only NodeServer

For development environment:

pm2 start ecosystem.config.js --only NodeServer

...And Boooom! guys

Sthenic answered 11/8, 2021 at 20:28 Comment(0)
N
4

if anyone has to pass any other script with a name here's how to do it.

pm2 start "npm run dev" --name myAppName
Natural answered 26/9, 2023 at 10:11 Comment(0)
R
2

Don't forget the space before start

pm2 start npm --[space]start

so the correct command is:

pm2 start npm -- start
Raulrausch answered 2/8, 2019 at 5:48 Comment(0)
S
2

It's working fine on CentOS 7

PM2 version 4.2.1

let's take two scenarios:

1. npm start //server.js

pm2 start "npm -- start" --name myMainFile

2. npm run main //main.js

pm2 start "npm -- run main" --name myMainFile
Schober answered 13/1, 2020 at 20:5 Comment(0)
D
2

To run PM2 with npm start method and to give it a name, run this,
pm2 start npm --name "your_app_name" -- start

To run it by passing date-format for logs,
pm2 start npm --name "your_name" --log-date-format 'DD-MM HH:mm:ss.SSS' -- start

Dehypnotize answered 9/5, 2020 at 8:14 Comment(0)
D
1

Unfortunately, it seems that pm2 doesn't support the exact functionality you requested https://github.com/Unitech/PM2/issues/1317.

The alternative proposed is to use a ecosystem.json file Getting started with deployment which could include setups for production and dev environments. However, this is still using npm start to bootstrap your app.

Dissatisfied answered 23/7, 2015 at 7:17 Comment(1)
What do you mean by that? However, this is still using npm start to bootstrap your app. Can you actually run npm start using pm2?Tiber
D
1
pm2 start ./bin/www

can running

if you wanna multiple server deploy you can do that. instead of pm2 start npm -- start

Display answered 30/3, 2019 at 8:0 Comment(0)
G
1

For my vite project on AWS EC2,

pm2 start npm -- run dev --host was only captured in the pm2 list but was not really running the npm run dev --host

I Had this error:

PM2        | 2023-09-03T02:36:50: PM2 log: Script /root/.nvm/versions/node/v18.17.1/bin/npm had too many unstable restarts (16). Stopped. "errored"
PM2        | 2023-09-03T02:37:01: PM2 log: App [npm:1] starting in -fork mode-
...
...

...So I swapped npm for yarn, so this worked in my case pm2 start yarn -- dev --host as it runs yarn dev --host

Gibun answered 3/9, 2023 at 3:21 Comment(0)
S
0

Now, You can use after:

pm2 start npm -- start

Follow by https://github.com/Unitech/pm2/issues/1317#issuecomment-220955319

Subsoil answered 25/3, 2017 at 14:48 Comment(1)
Can you expand your answer? Advice from How to answer: Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.Grendel
R
0

for this first, you need to create a file run.js and paste the below code on that.

const { spawn } = require('child_process');
//here npm.cmd for windows.for others only use npm
const workerProcess = spawn('npm.cmd', ['start']); 

  workerProcess.stdout.on('data', function (data) {  
      console.log('stdout: ' + data);  
   });  
 workerProcess.stderr.on('data', function (data) {  
      console.log('stderr: ' + data);  
   });  
 workerProcess.on('close', function (code) {  
      console.log('child process exited with code ' + code);  
   });  

and run this file with pm2.

pm2 start run.js 
  • List item
Retrospection answered 21/10, 2022 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.