automatic restart of node.js apps via git commit messages

0 Replies

When updating our node.js applications we usually had to login on the webserver, pull the updates from git and restart the server. To make this easier we decided to write a git hook that would automate the process. The following scripts work in combination with gitlab and pm2. They will pull from git if you write +release into your commit message. They will restart the server if you write +restart into your commit message. They will also pull and restart if you close a gitlab issue in your commit message with close, closes, fix, fixes or fixed The script assumes your applications are checked out into /var/node, if you use another directory you need to replace it. /var/opt/gitlab/git-hooks/post-receive:

#!/bin/bash
#
export HOME=/var/opt/gitlab

PROJECT_GIT=$1  
PROJECT_PM2=$2

pull=0  
restart=0  
while read oldrev newrev refname; do  
    revs=`git rev-list --reverse $newrev ^$oldrev`
    for rev in $revs
    do
        msg=`git log $rev -1`
        cmp1=`echo $msg | sed "s/+release//"`
    cmp2=`echo $msg | sed "s/(close|closes|closed|fix|fixes|fixed) #[0-9]//"`
        cmp3=`echo $msg | sed "s/thisistheoriginialcommitmessage//"`
        cmp4=`echo $msg | sed "s/+restart//"`
        #echo "msg: [$msg] [$cmp1] [$cmp2]"
    if [ "$cmp1" != "$cmp2" ]
        then
            echo "Update required @$rev"
        let pull=1
        fi

    if [ "$cmp3" != "$cmp4" ]
        then
            echo "Restart required @$rev"
        let restart=1
        fi
    done
done

echo "Pull? $pull - Restart? $restart"  
if [ $pull -eq 1 ]  
then  
    echo "Updating server"
    pushd /var/node/$PROJECT_GIT
    pwd
    echo "Running npm"
    npm install
    echo "Runnin bower"
    HOME=/var/opt/gitlab bower install -s
    export GIT_DIR=/var/node/$PROJECT_GIT/.git
    echo "Updating git"
    git pull
    popd
fi

if [ $restart -eq 1 ]  
then  
    pm2 restart $PROJECT_PM2
fi  

Call the above script from but make sure to replace /var/opt/gitlab/git-data/repositories/yourgitlabsgroup/yourgitlabproject.git/hooks/post-receive:

#!/bin/bash
PROJECT_PM2=title of your app in pm2  
PROJECT_GIT=directory of your app in /var/node  
/var/opt/gitlab/git-hooks/post-receive $PROJECT_GIT $PROJECT_PM2

Also make sure both script will be executable by your git user.

managing your node processes with pm2

Share Your Thoughts