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