'How to pass NODE_ENV=production to pm2?

I have this node app deployed and runs fine with NODE_ENV=production yarn start.

I can demonize the app using

pm2 start npm -- start

but then it defaults to NODE_ENV=development config.

And when I use

pm2 start npm -- start NODE_ENV=production

It still starts with development config.

Also I tried passing the env using a process.yml file

apps:
  - script   : index.js
    watch: true
    instances: 4
    env    :
      NODE_ENV: production

but pm2 start npm -- start process.yml still loads the development configs.

How can I fix this?



Solution 1:[1]

The reason you might be facing this is because you would have started pm2 with development once. Now it will use that env until you kill it. Following these steps should help

  1. ./node_modules/.bin/pm2 kill
  2. NODE_ENV=production ./node_modules/.bin/pm2 start server.js

You can also use --update-env. From the official docs

By default we want that PM2 doesn’t change process environment while restarting or reloading so they are immutable. If you want to update them, you must use --update-env :

Solution 2:[2]

try this: export NODE_ENV=production&&pm2 start server.js

Solution 3:[3]

export NODE_ENV=production && pm2 start ecosystem.config.js 

Following line helped me! Thanks to #mehdi parastar and #abhinavd

Solution 4:[4]

You can solve it using this command (with double quotes):

sudo pm2 start "NODE_ENV=production yarn start"

Solution 5:[5]

Try this, if you are using a pm2, the below code works for me

sudo NODE_ENV=production pm2 start app.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AbhinavD
Solution 2 mehdi parastar
Solution 3 Selim
Solution 4 tdy
Solution 5 ND NAVEEN