Search code examples
javascriptnode.jsmicroservicespm2node-dev

How to run 2 application with different node version using pm2


I am following microservice architecture for my application.

I have 7 microservices few running on the node and a few are on python and go. 2 of the microservice have multiple instances (i.e. running in cluster mode).

All microservices are managed by PM2.

Now I am upgrading the node versions of services one by one. Whatever I looked on the internet it says I can use 2 versions only on fork mode. How to run pm2 services on two different versions in cluster mode?

I do not want to use a load balancer or docker.


Solution

  • You can use nvm to manage your different node version you nedd, then for starting node apps, do that:

    sudo pm2 start app.js --interpreter=/home/user/.nvm/v4.4.2/bin/node
    

    Naturaly, replace node nvm path according to your case.

    For installing nvm: https://github.com/nvm-sh/nvm#installing-and-updating

    Once installed to install node versions:

    // Install last 16.x
    nvm install 16
    
    // Spécific version
    nvm install 16.14.2
    
    // List installed 
    nvm list
    

    UPDATE

    If --interpreter is not usable with cluster mode, you can try this trick.

    1 - localize pm2 binary with ``which pm2`` command
    2 - Change directory to the pm2 binary directory: ``cd /path/to/pm2``
    3 - make a copy of pm2 binary: ``cp pm2 pm2-node-xx`` replace xx with node version you want
    4 - verify that copied binary have executable flag, if not make a ``chmod +x`` on it
    5 - edit the copied binary file an on first line modify the shebang. Replace ``#!/usr/bin/env node`` by ``#!/home/ubuntu/.nvm/versions/node/v13.14.0/bin node``
    

    Once this done, you should have a new pm2 binary using another node version. You'll be able to launch a node script with pm2-node-xx start app.js.

    You will have two pm2 daemon running, one per node version. You can reproduce this recipe for all node version you need.