7

When I run my nodejs application on my Ubuntu Linux server using node server.js it works correctly, and outputs the value of the environment variable $db using process.env.db.

However, the app breaks when running sudo pm2 start server.js, seeing the environment variable as undefined.

I've tried adding the variable in the following files:

  • etc/environment: db="hello"
  • ~/.ssh/environment : db="hello"
  • ~/.bashrc : export db="hello"

I've also rebooted and run source ~/.bashrc to ensure the variable is available.

I think I've tried everything mentioned here, I don't know what else to do:

Community
  • 1
  • 1
Richard
  • 14,798
  • 21
  • 70
  • 103

3 Answers3

10

Note that saying source ~/.bashrc you are loading the variables on your current user. However, when you say sudo ... you are running with the user root, so this won't change.

What you can do is to use sudo with -E:

sudo -E pm2 start server.js

From man sudo:

-E, --preserve-env
             Indicates to the security policy that the user wishes to reserve their
             existing environment variables.  The security policy may eturn an error
             if the user does not have permission to preserve the environment.
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Thanks, this worked. But I don't understand why, surely having the variable in etc/environment means that the root user can see it? I thought the problem was the opposite - that my user couldn't see it and therefore I had to add the variable to the ~/ files as well as etc/environment. – Richard Jan 20 '16 at 11:00
  • This probably has to do with the fact you are saying `db="hello"` in `/etc/environment`. If you do not define it with `export`, the variable is not available to the sub-processes. Saying `export db="hello"` in that file should make it. – fedorqui Jan 20 '16 at 11:01
  • I don't think so, from here: https://help.ubuntu.com/community/EnvironmentVariables - "It is not a script file, but rather consists of assignment expressions, one per line." But anyway, it doesn't matter, I know how to get it to work now, thanks. – Richard Jan 20 '16 at 11:08
  • `/etc/environment` is loaded during login/authentication. Isn't set automatically when is modified. – Deoxyseia Oct 07 '21 at 15:19
2

Please refer to this thread https://github.com/Unitech/pm2/issues/204

Seems like your environment variables get's cached.

Vlad Miller
  • 2,255
  • 1
  • 20
  • 38
  • As suggested I tried running **sudo pm2 kill** to shutdown the whole process and then restarted it, to get the new variable, but it still doesn't work. I've rebooted the machine too so I doubt this is the problem. – Richard Jan 20 '16 at 10:56
0

I deleted the pm2 process and started it again as normal. simply restarting the process didn't work though.

mdehghani
  • 504
  • 1
  • 7
  • 23