简体   繁体   English

使用 pm2 将环境变量传递给 node.js

[英]Passing environment variables to node.js using pm2

I am trying to pass some arguments to my Express application which is run by pm2.我正在尝试将一些 arguments 传递给我由 pm2 运行的 Express 应用程序。 There wasn't any hint in their documentation to do so, but apparently it's possible to pass some EV to your node application like SOME_STUFF=xxx pm2 start app.js .他们的文档中没有任何提示这样做,但显然可以将一些 EV 传递给您的节点应用程序,例如SOME_STUFF=xxx pm2 start app.js

Note - after updating environment variables in your environment, you must do the following:注意 - 在您的环境中更新环境变量后,您必须执行以下操作:

pm2 restart all --update-env pm2 重启所有 --update-env

ask me how I know...问我怎么知道...

Edit: also look for a .env file in the node source directory...编辑:还要在节点源目录中查找 .env 文件...

It's actually possible and I'm pretty sure it was in PM2's documentation some time ago.这实际上是可能的,而且我很确定前段时间在 PM2 的文档中。

Anyways, that's what you need to do:无论如何,这就是你需要做的:

pm2 start app.js -- -some_stuff xxx

Basically, add -- and then you can add your own app parameters.基本上,添加--然后您可以添加自己的应用程序参数。

Managed to find the source, it was hidden quite well: http://pm2.keymetrics.io/docs/usage/quick-start/#42-ways-of-starting-processes设法找到源头,它隐藏得很好: http : //pm2.keymetrics.io/docs/usage/quick-start/#42-ways-of-starting-processes

I was having issues passing parameters using pm2 start app.js -- -some_stuff xxx so I opted to do this instead: SOME_STUFF=xxx OTHER_STUFF=abc pm2 start app.js .我在使用pm2 start app.js -- -some_stuff xxx传递参数时遇到问题,所以我选择这样做: SOME_STUFF=xxx OTHER_STUFF=abc pm2 start app.js

Then when I ran pm2 logs I was able to see that my app successfully started and that the environment variables were set correctly where as before I was seeing errors around these variables when I ran pm2 logs .然后,当我运行pm2 logs我能够看到我的应用程序成功启动,并且环境变量设置正确,就像以前一样,我在运行pm2 logs时看到这些变量周围的错误。

You should pass ENV in ecosystem.config.js您应该在生态系统.config.js 中传递 ENV

ecosystem.config.js (in the root) ecosystem.config.js(在根目录中)

module.exports = {
  apps: [
    {
      name: "project-name",
      exec_mode: "cluster",
      instances: "1",
      script: "./server/index.js", // your script
      args: "start",
      env: {
        NODE_ENV: "production", 
        SOME_ENV: "some_value"...
      },
    },
  ],
};

In the console:在控制台中:

pm2 run ecosystem.config.js

There is information about configuration of ENV in PM2 official documentation PM2官方文档中有关于ENV的配置信息

环境变量并不总是更新,除非您强制它们更新。

SOME_STUFF=xxx pm2 start app.js --update-env

My node app (sveltekit build) starts in my ubuntu server when I use当我使用时,我的节点应用程序(sveltekit build)在我的 ubuntu 服务器中启动

node build/index.js

and includes enviroment variables并包括环境变量

so with pm2 I found that my app starts with envs starting it:所以使用 pm2 我发现我的应用程序以 envs 开头:

pm2 "node build/index.js"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM