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:
I 've gone through the same problem it's because of the integrated terminal in visual studio and visual studio code it seems like they don't have access to any of these variables unless you run the editor in Admin mode.so to solve this problem you just need to start your editor in Amin mode
Make sure you have this code in app.js file
> const path = require('path'); require('dotenv').config({ path:
> path.join(__dirname, '.env') });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With