简体   繁体   中英

PM2 change cluster processes size at runtime

does anyone know if it is possible to change in NodeJS PM2 the number of cluster processes for an application at runtime?

regards Philipp

You can use pm2 scale to scale vertically the number of process at runtime, note that it only work with cluster mode . Example :

  • pm2 scale APPNAME 2 will scale the process to exactly 2 instances.
  • pm2 scale APPNAME +2 will add two process.
  • pm2 scale APPNAME -1 will remove one process.

source link

specify pm2 settings in json format:

{
 "apps": [{
    "name": "server",
    "script" : "index.js",
    "instances": 2,
    "exec_mode: "cluster",
    "cwd": "/path/to/script"
 }]
}

start the server:

pm2 start application.json

suppose you want to add 2 more instances, just run the same command again:

pm2 start application.json

check the processes list:

pm2 list

to test that all 4 instances are run in cluster mode:

pm2 restart server

it will restart each of the 4 processes.

At runtime (after the application is started), there are 2 ways to "scale" the application:

1) With the command line (documented here under "Scaling your cluster in realtime"), like this:

pm2 scale <app name> <n>

Note that can be a consistent number which the cluster will scale up or down to. It can also be an addition such as pm2 scale app +3 in which case 3 more workers will be added to the cluster.

2) With the Programmatic API (docs are here , but scale is not documented). As it's not documented, here's how you do it:

pm2.scale(<APPNAME>, <SCALE_TO>, errback)

Note that is the number that will be scaled up or down to, not the number added or removed. Here's a full example of connecting to and scaling to 4 instances:

var pm2 = require('pm2');
pm2.connect(function (err) {
    pm2.scale('appname', 4, function(err, procs) {
        console.log('SCALE err: ', err);
        console.log('SCALE procs: ', procs);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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