【问题标题】:Difference in environment variable usage between development and production modes?开发模式和生产模式之间的环境变量使用差异?
【发布时间】:2020-02-24 01:43:48
【问题描述】:

我正在学习如何将一个简单的后端 node.js 项目部署到生产环境,在我的例子中是 heroku。我在 .env 文件中看到了有关环境变量的注释:

The environment variables defined in dotenv will only be used when the backend is not in production mode, i.e. Heroku.

We defined the environment variables for development in file .env, but the environment variable that defines the database URL in production should be set to Heroku with the heroku config:set command:

heroku config:set MONGODB_URI=mongodb+srv:...

如果使用 heroku 意味着我的后端处于生产模式,我的 .env 文件如何使用 heroku config:set MONGODB_URI=mongodb+srv... 环境变量?第一句话说明环境变量只用于开发模式。

我理解错了什么?开发模式和生产模式都使用了环境变量,我看的注释的措辞有误吗?

【问题讨论】:

    标签: node.js heroku environment-variables development-environment production-environment


    【解决方案1】:

    我理解错了什么?开发模式和生产模式都使用了环境变量,我看的注释的措辞有误吗?

    环境变量用于所有场景,但仅在本地开发模式下,它们是从文件中读取的。 dotenv 是一个允许从文件中读取环境变量的包。

    在生产模式下,Heroku 本质上是这样做的,例如:

    PORT=9999 节点索引.js

    试试看,你可以通过以下方式访问 Node 内部的这个变量:

    console.log(process.env.PORT);
    // 9999
    

    环境变量只是整个进程可用的全局变量。

    【讨论】:

    • 如果.env文件只在本地开发模式下读取,如果heroku config:set MONGODB_URI...在我的.env文件中,我的应用程序的生产模式如何工作?一旦我部署到 Heroku,我的应用程序如何使用 MONGODB_URI 环境变量,因为我的应用程序现在处于生产模式?
    【解决方案2】:

    我认为这是说.env 中的环境变量将在您进行开发(而不是 Heroku)时使用,并且如果您确实想在 Heroku 中使用您的环境变量,您需要通过heroku config:set ... 进行操作.

    【讨论】:

    • 那么在我的 .env 文件中使用 heroku config:set... 将允许在我的 .env 文件中的环境变量在生产模式下使用?
    • 不,不在您的 .env 文件中。我对 Heroku 不是很熟悉,但我假设您会在终端中使用该命令,而 Heroku 会在他们的服务器上使用该命令。
    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2013-08-06
    • 1970-01-01
    • 2017-04-16
    • 2019-11-03
    相关资源
    最近更新 更多