1

The PM2 documentation — Load-balancing (cluster mode)

The PM2 documentation — Load-balancing (cluster mode)

The built-in load-balancer provides networked Node.js applications (http(s)/tcp/udp server) to be scaled across all CPUs available, without any code modifications.

According to the PM2 documentation, PM2 also supports load-balancing across Node.js processes. Yet, the most common practice for load-balancing, inarguably, is using a load-balancing reverse proxy, such as Nginx, even if you’re using PM2.


Question

Say you have a single machine, and you’re using PM2 to make full use of multiple CPU cores spawning several Node.js processes and keep them up. Why would you use a load-balancing reverse proxy to distribute load when PM2 also supports it? Are the two “load-balancing” different things?


In other words,

why would you do

pm2 start app.js -f --3000
pm2 start app.js -f --3001
pm2 start app.js -f --3002
pm2 start app.js -f --3003

and

upstream app_servers {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002;
    server 127.0.0.1:3002;
}

server {
    listen 80;
    ……
}

instead of just doing

pm2 start app.js -i max

?

  • 1
    The ONLY reason is that it allows you to scale by starting up more machines. The HTTP load balancer allows you to transparently and quickly add more servers to your system. Otherwise PM2 load balancing is better and slightly faster (due to not needing to parse HTTP twice - PM2 is purely TCP load balancing) – slebetman May 19 '21 at 14:34
  • @slebetman, I see. May I ask another question? Say you have _several_ multicore machines, each of which having multiple Node.js processes. Should I make Nginx solely do load-balancing across the whole processes, or only just across the machines and have PM2 do the local load distribution across processes? – Константин Ван May 19 '21 at 14:45
  • 1
    At that point there is a slight speed advantage of not using PM2 load balancing since you are only running one load balancing algorithm instead of two. But either way it's not much of a difference. What does make a difference is maintainability. It depends on which you or your tools feel easier to manage. With no PM2 the whole setup is simpler but leads to a slightly more complicated or bloated nginx config. The other leads to a simpler or smaller nginx config but you now have an additional thing to configure. But that may not matter since you will need to configure PM2 anyway.. so it depends – slebetman May 20 '21 at 02:06

0 Answers0