Automate Git deployment to remote server - Web hooks

Hello, today in this post I will show you how I deploy Git project to the production (or development) server, and push changes to them automatically through git web hook wherever I made changes through the repo. I use this method to see live changes to the project server.

To be precise, I made this Ghost theme locally and when everything is okay, I push to the server and see live changes. So that I don't need to re-upload theme whenever changes I made. If you're in similar goal to archive, you can follow the tutorial below, or else, you can alter it based on your needs.

Requirement

In order to follow this tutorial, you need a remote server available and Ghost installation ready. Make sure you install Ghost through Ghost-CLI, as it much easier to install, to troubleshoot and much more.

  1. VPS DigitalOcean referral code.
  2. Ghost CMS install (follow installation instruction)

In remote server

Login to your remote server (not root).
2. Create:

mkdir ~/deployment-folder.git
cd ~/deployment-folder.git
git init --bare
nano hooks/post-receive
chmod +x hooks/post-receive

Add the following in ~/deployment-folder.git/hooks/post-receive

#!/bin/bash
TARGET="/var/www/ghost/content/themes/mythemes" # deploy-folder
GIT_DIR="/home/user/deployment-folder.git"
BRANCH="master"

while read oldrev newrev ref
do
        # only checking out the master (or whatever branch you would like to deploy)
        if [[ $ref = refs/heads/$BRANCH ]];
        then
                echo "[+] Ref $ref received. Deploying ${BRANCH} branch to production..."
                sudo git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
		echo "[+] Initializing folder .."
		sudo chown -R ghost:ghost $TARGET
		sudo chmod 755 $TARGET
		echo "[+] Restarting ghost service"
		cd /var/www/ghost ; ghost restart
        else
                echo "[-] Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
        fi
done

In local machine

  1. In your repository:
    Change directory to git project folder:
cd mythemes

To set a new remote. In this case remote called as 'production' you can change to whatever you want.

git remote add production [email protected]:/home/user/deployment-folder.git
git checkout master
git push origin master # push to github
git push production master # push to server

To view (verify) remote:

git remote -v

On push to remote production, everything will automate and make changes to Ghost theme on web server.