Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jenkins to restart PM2?

i'm running my node.js app on the linux server using PM2, with a config file, like this:

PM2 start mywebsite.config.js

all is good. but now i want to add jenkins to the picture. i'm running a pipeline project in jenkins, using Jenkinsfile. All working fine except for the last command, that should restart the app, to make the new version live:

stage('Restart PM2') {  
  steps {
    sh 'pm2 restart all'  }
  }
}

and this command fails. here is the log output:

+ pm2 restart all 
Use --update-env to update environment variables 
[PM2][WARN] No process found 
< empty pm2 log table here> 
Use `pm2 show <id|name>` to get more details about an app

I understand that PM2 is working per user. means, that the user who ran the first command (start) is the one that should run the restart as well. but how to do this?

like image 528
Ron Al Avatar asked Jun 16 '19 04:06

Ron Al


2 Answers

To run pm2 restart all from Jenkins you need to:

  1. Configure your system to run sudo from jenkins (https://sgoyal.net/2016/11/18/run-a-shell-from-jenkins-using-sudo-ubuntu/)

  2. Make a symbolic link to the .pm2/ folder, in my case(Ubuntu) it was at /root/.pm2 so i run

sudo ln -s /root/.pm2/ /var/lib/jenkins/

NOTE: /var/lib/jenkins if the default jenkins root directory, you can check yours on Jenkins configuration

  1. after that you can go to jenkins and setup a shell command, in my case i did:

#!/bin/sh echo "RESTARTING ALL" sudo pm2 restart all echo "ALL RESTARTED"

NOTE: if you have a .pm2 folder already in your jenkins root directory rename it so you can do the symbolic link

Hope this helps

like image 105
Isan Rodriguez Trimiño Avatar answered Sep 22 '22 08:09

Isan Rodriguez Trimiño


Instead of restarting PM2 through you jenkins code, let PM2 do it by itself, using the watch flag. in your config file, set watch to be true. You may want to add a relatively new flag called watch-ignore. that's an array, with files to be ignored by the watch. add your log file and error file to this list. otherwise, any logged information will cause your node app to restart endlessly. after doing these changes to the config file, run pm2 again with the config. remove the restarting code from Jenkinsfile, you don't need that anymore, pm2 will detect the new version and will reload the app!

like image 21
Amir Gilboa Avatar answered Sep 20 '22 08:09

Amir Gilboa