环境变量未加载到Node.js中的process.env
我正在构建一个nodejs api,并已将 dotenv
软件包设置为dev依赖项,以将变量加载到开发人员的本地计算机上的 process.env
中.
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.
请注意,当我登录时,我使用 sudo -i
来作为 root
.
Note that when I log in I use sudo -i
to operate as root
.
我的意图是在部署过程中,将在我的Ubuntu主机中的/etc/environment
下设置环境变量,然后将其直接加载到进程中,然后该应用程序将针对该配置运行.
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.
为此,我在 server.js
的开头一行:
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();
}
并且将指示开发人员为他们的系统添加 NODE_ENV
的环境变量.
And developers will be instructed to add an environment variable to their system for NODE_ENV
.
现在,在我的Ubuntu EC2实例中,我已经设置了/etc/environment
以具有所需的环境变量(请注意,此处的NODE_ENV为'dev'只是为了避免运行dotenv):
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
当我重新启动并运行 printenv
时,它们都是按文件填充的.
And when I reboot and run printenv
they are all populated per the file.
我已设置 pm2
来直接从 server.js
运行我的应用程序,而无需任何其他配置,因为据我了解, process.env
是从环境变量自动填充的.
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.
但是,当我记录来自process.env的值时,我只是对所有内容都为空:
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?
注意:按照下面的答案,我在启动pm2之后错误地设置了环境变量,因此pm2缓存丢失了它们
Note: Per the answer below, I had mistakenly setup my environment variables AFTER starting pm2, and as such pm2 caching was missing them
问题是 pm2
缓存环境变量.
您必须这样做:
# 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: