Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set Linux environment variables so that pm2 can see them for node.js apps?

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:

  • https://unix.stackexchange.com/questions/117467/how-to-permanently-set-environmental-variables
  • https://github.com/Unitech/pm2/issues/867
  • Why does an SSH remote command get fewer environment variables then when run manually?
  • https://serverfault.com/questions/389601/etc-environment-export-path
like image 851
Richard Avatar asked Jan 20 '16 10:01

Richard


People also ask

Do we need to set environment variables for node js?

You really do not need to set up your own environment to start learning Node. js. Reason is very simple, we already have set up Node.


2 Answers

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.
like image 86
fedorqui 'SO stop harming' Avatar answered Sep 27 '22 19:09

fedorqui 'SO stop harming'


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

Seems like your environment variables get's cached.

like image 21
Vlad Miller Avatar answered Sep 27 '22 21:09

Vlad Miller