简体   繁体   中英

Environment Variables not loading to process.env in Nodejs

I'm building out a nodejs api and have setup the dotenv package as a dev dependency to load the variables to process.env on developer's local machines.

Note that when I log in I use sudo -i to operate as root .

My intent is that during deployment, environment variables would be set in my Ubuntu host under /etc/environment , loaded directly in to the process, and then the app would just run for that configuration.

To do this, I have a line at the start of server.js :

if(process.env.NODE_ENV === 'development') {
    logger.info("Loading dotenv for development environment")
    require('dotenv').config();
}

And developers will be instructed to add an environment variable to their system for NODE_ENV .

Now, in my Ubuntu EC2 instance I've setup the /etc/environment to have the environment variables I want (note that NODE_ENV being 'dev' here is just to avoid running dotenv):

PORT=MYPORT
NODE_ENV=dev
APP_SECRET_KEY='MYSECRET'
APP_DATABASE_LOGIN=MYLOGIN
APP_DATABASE_PASSWORD='MYPASS'
APP_DATABASE_HOST=MYHOST
APP_DATABASE_NAME=MYDB
APP_DATABASE_PORT=MYDBPORT

And when I reboot and run printenv they are all populated per the file.

I have setup pm2 to run my application directly from server.js without any additional configuration because as I understand it, process.env is populated automatically from environment variables.

However, when I log the values from process.env, I just get null for everything:

logger.info({
    connectionConfig: {
        host: process.env.APP_DATABASE_HOST
        , login: process.env.APP_DATABASE_LOGIN
        , port: process.env.APP_DATABASE_PORT
        , databaseName: process.env.APP_DATABASE_NAME
    }
});

Is there something wrong with the configuration as-is here?

Note: Per the answer below, I had mistakenly setup my environment variables AFTER starting pm2, and as such pm2 caching was missing them

The issue is that pm2 caches the environment variables.

You have to do:

# all apps
pm2 restart all --update-env
# specific app
pm2 restart {pid} --update-env

If for some reason that doesn't work, the documented way is:

pm2 reload ecosystem.json --update-env

You can read more in here :

我遇到了同样的问题,这是因为 Visual Studio 和 Visual Studio 代码中的集成终端,除非您在管理模式下运行编辑器,否则它们似乎无法访问任何这些变量。所以要解决这个问题,您只需要在 Amin 模式下启动你的编辑器

Make sure you have this code in app.js file

> const path = require('path');  require('dotenv').config({ path:
> path.join(__dirname, '.env') });

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