Git Hooks for Node.JS

We need to create git hooks to deploy node applications directly by pushing to a specific origin. For this, we need a folder for git repo and a folder for hosting. For continuous execution of node.js code, we will use PM2. Our environment will be as follows;

Git Repo: /var/repo/git_repo

Hosting Folder: /var/www/hosting

Git Branch: main 

 

Following steps to be followed;

Step 1: Server-side

# Install PM2 on server 

$ npm install pm2 -g

# Initialize Git repo

$  git init --bare /var/repo/git_repo

# Cloning the repo to hosting folder - this will give warning of cloning empty repo

$ git clone /var/repo/git_repo /var/www/hosting

# Editing post receive hook of git repo

$ vim /var/repo/git_repo/hooks/post-receive

#!/bin/bash
echo 'post-receive: Triggered'
cd /var/www/hosting
git --git-dir=/var/repo/git_repo --work-tree=/var/www/hosting checkout main -f
echo 'post-receive: Cloning complete' 
cd /var/www/hosting \
&& npm install \
&& echo 'post-receive: installation done' \
&& pm2 --silent  delete 'myapp' \
&& echo 'starting server' 
pm2 start app.js --name 'myapp'

$ chmod ug+x /var/repo/git_repo/hooks/post-receive

Step 2: Client side

$ git remote add prod ssh://root@iop/var/repo/git_repo

$ git push prod main

Comments

Popular posts from this blog

Running NodeJs API with Apache & PM2 on Ubuntu