Deploy static sites with Git

In the following article I will describe the method I use to deploy static websites to production and staging environments with the help of git hooks.

Requisites

  • Web server to host your static site.
  • Git installed on your local and remote machines.
  • SSH password-less access configured.
  • Terminal.

Server Setup

For this configuration you will need atleast two folders on the remote server. One of the folders holds the git bare repository and the other will hold your static site public files. I like to use the repository name for the corresponding folders but feel free to name it as you prefer.

As an example our repository name is “my-foo”.

Without further due lets get started:

Access your server

ssh your-web-server

Create the new folders

mkdir my-foo my-foo.git

Setup the remote git repository

The actual website files will be served from the my-foo folder. That is why we create a bare git repository.

cd ~/my-foo.git
git init --bare

Create a post-receive hook

cd ~/my-foo.git/hooks
vim post-receive

Insert this script and adapt to your needs. Make sure you check the variables on the top.

#!/bin/bash
TARGET="/home/user/my-foo"       # Where to deploy the website
GIT_DIR="/home/user/my-foo.git"  # Git repository location
BRANCH="master"                  # Accepted branch

while read oldrev newrev ref
do
  if [[ $ref = refs/heads/$BRANCH ]];
  then
    echo "Ref $ref received. Deploying ${BRANCH} branch to production."
    git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
  else
    echo "Ref $ref received. No changes: only the ${BRANCH} branch may be deployed on this server."
  fi
done

Make sure the post-receive hook is executable.

chmod +x post-receive

Local setup

Assuming you already have a git repository locally you will need to add the new remote for deployment.

cd ~/my/foo/path
git remote add deploy ssh://user@your-web-server:/home/user/my-foo.git

Make sure the folder path matches the folder that you created with the bare git repository on the remote server.

Time to deploy!

git add -A
git commit -m "Deploy message..."

git push deploy master

Your website is now live/updated and deployed on the my-foo folder!

This setup allows you to keep commiting to your origin like a Github/Bitbucket/Gitlab remote and only deploy when you want.

To summarize:

git push origin master # Push code to remote repository
git push deploy master # Deploy the website

If you have any question, feel free to drop me an email or comment below.

Written on August 20, 2017