简体   繁体   中英

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:

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.

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

Seems like your environment variables get's cached.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM