Home > Software design >  how to load balance api backend on different ports with pm2
how to load balance api backend on different ports with pm2

Time:12-20

Let's say I have a simple api backend that listens on port 3000

const app = express();

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(3000, () => {
  console.log('API listening on port 3000');
});

I want to load balance this, so I'm using pm2 for that

pm2 npm start --name apis -i 2 -- start

pm2 ls shows me 2 instances running in cluster mode, but one's errored out because port 3000 is being used by the first instance (obviously)

in this case, what's the right way for me to load balance or specify different ports?

CodePudding user response:

You can use the PM2 ecosystem instead of running manual commands.

// index.js
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(3000, () => {
  console.log('API listening on port 3000');
});
// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: "apis",
      script: "index.js",
      instances: "2",
      autorestart: true,
      max_memory_restart: "1G",
      env: {
        PORT: 3000,
      },
    }
  ]
}

Start the project by running: pm2 start ecosystem.config.js

For more about pm2 multiple instance

CodePudding user response:

found a way.

pm2 has an option to increment variables with each instance, so with this config, my backends started on incremented ports each

module.exports = {
    apps: [
        {
            name: "apis",
            script: "npm",
            args: "start",
            instances: 4,
            exec_mode: "cluster",
            increment_var: "PORT",
            env: {
                PORT: 3000,
            },
        },
    ],
};
  • Related