Search code examples
node.jsreactjspm2dotenv

How can I load environment variables via command line when running a node.js app in cluster mode with PM2?


When starting my application with node, I typically run:

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

When using PM2 in fork mode I can start the application like so:

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

If I try to run the application in cluster mode though, it seems to ignore node-args and fails to load the environment variables.

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

What would be the proper workaround to solve this issue without adding it explicitly to the application code? Should I even be doing it this way to begin with?

Update: It appears pm2 ecosystem is the correct way to inject command line args if you're looking to run apps in cluster mode. Using node_args: '-r dotenv/config' I was able to achieve the desired result. Thanks!

P.S. Make sure you set your environment to production or you may run into unintended issues when launching the app.


Solution

  • Can you use an ecosystem file for PM2?

    Running the following will generate a basic config file.

    pm2 ecosystem
    

    The default file is included below:

    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 : '[email protected]:repo.git',
          path : '/var/www/production',
          'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production'
        }
      }
    };
    

    According to the example in the documentation, you can add an "exec_mode" to the json file. See below:

    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"
      }]
    }
    

    Modify the file as needed and run with:

    pm2 start ecosystem.config.js