Pm2: Environment variables do not work OR are cached

Created on 3 Dec 2013  路  5Comments  路  Source: Unitech/pm2

On CentOS v6.4, Node.js v0.10.21

NODE_ENV=production node run.js

Doesn't set process.env.NODE_ENV to production, it is undefined
I found a workaround by using -x switch:

NODE_ENV=production pm2 -x -i 1 start run.js

Then I have another problem...when I change the an ENV variable, the change doesn't happen, for example if I execute the following command after running the application in production mode:

pm2 stop all
NODE_ENV=staging pm2 -x -i 1 start run.js

In my application process.env.NODE_ENV is equal to production, it should be equal to staging.
I tried:

pm2 stop all
sudo service pm2 stop
sudo service pm2 start
NODE_ENV=staging pm2 -x -i 1 start run.js

The same situation, process.env.NODE_ENV is equal to production

The solution that I found to work is:

pm2 stop all
sudo service pm2 stop
sudo rm -rf /root/.pm2
sudo rm -rf /home/username/.pm2
sudo service pm2 start
NODE_ENV=staging pm2 -x -i 1 start run.js

After the above commands, my application finally sees process.env.NODE_ENV as equal to staging.

  • [ ] Write test that properly checks if environment variables are properly passed
  • [ ] Write test that properly checks that environment variables are not cached
  • [ ] Write fixes for the above issues

Most helpful comment

use --update-env when you want to update the environment

All 5 comments

Yep this is normal in "cluster_mode". As pm2 wrap your code to his own context (and own variables) you get what was already there when launching it.

$ pm2 kill
$ NODE_ENV=production pm2 start app.js

Here it runs in "fork" mode and apparently environment variables are cached...
Is there any way to make sure it doesn't get cached. This is annoying to figure out.

use --update-env when you want to update the environment

Shouldn't it be by default to refresh environment variables? You don't expect it to be outdated.

Once you start your application in production mode (let's say NODE_ENV=production pm2 start app.js) I'm sure you prefer to keep this variables in memory and not get it overridden on restart

Was this page helpful?
0 / 5 - 0 ratings