在PM2集群模式下运行node.js应用程序时,如何通过命令行加载环境变量?

使用节点启动应用程序时,通常运行:

node -r dotenv/config ./build/index.js

在fork模式下使用PM2时,我可以像这样启动应用程序:

pm2 start --node-args="-r dotenv/config" build/index.js --name API

但是,如果我尝试在集群模式下运行该应用程序,它似乎会忽略node-args并且无法加载环境变量。

pm2 start --node-args="-r dotenv/config" build/index.js -i max --name API

在不显式将其添加到应用程序代码中的情况下,解决该问题的正确方法是什么?我应该以这种方式开始吗?

baogang888999 回答:在PM2集群模式下运行node.js应用程序时,如何通过命令行加载环境变量?

您可以将生态系统文件用于PM2吗?

运行以下内容将生成一个基本的配置文件。

pm2 ecosystem

默认文件包括在下面:

module.exports = {
  apps : [{
    name: 'API',script: 'app.js',// Options reference: https://pm2.keymetrics.io/docs/usage/application-declaration/
    args: 'one two',instances: 1,autorestart: true,watch: false,max_memory_restart: '1G',env: {
      NODE_ENV: 'development'
    },env_production: {
      NODE_ENV: 'production'
    }
  }],deploy : {
    production : {
      user : 'node',host : 'localhost',ref  : 'origin/master',repo : 'git@github.com:repo.git',path : '/var/www/production','post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
    }
  }
};

根据文档中的示例,您可以在json文件中添加“ exec_mode”。见下文:

module.exports = {
  apps : [{
    name        : "worker",script      : "./worker.js",watch       : true,env: {
      "NODE_ENV": "development",},env_production : {
       "NODE_ENV": "production"
    }
  },{
    name       : "api-app",script     : "./api.js",instances  : 4,exec_mode  : "cluster"
  }]
}

根据需要修改文件并运行:

pm2 start ecosystem.config.js
本文链接:https://www.f2er.com/2836114.html

大家都在问