J Scott Smith

Automatic Deployments with Git Hooks

Articles - January 17th, 2015

Overview

So you’re tired of manually deploying your site/app and would like to automate all the things. Well, the simplest way (that I know) is to use a Git post-receive hook. In order to do this you will need to be using Git to version control your site and you will need to have Git installed on your server. This process was entirely borrowed from this great article: How To Set Up Automatic Deployment with Git with a VPS. Please read that for a more informative guide. Or not.

Basic Breakdown

  1. Create a bare repo on your server.
  2. Create a folder in your www directory for your live website.
  3. Setup a post-receive hook.
  4. Add a new remote to your local Git repo.
  5. Push to the new remote to deploy all the things.

Creating the Live Directory

You will need a directory to hold your site’s files. Most likely it will be in /var/www/site.com/. So cd there and create that empty directory.

Creating the Bare Repo

First, create a repo directory within /var on an Ubuntu server. Then, within that create a folder for your sites repo. Finally, within that folder initialize a bare Git repo.

cd /var
sudo mkdir repo && cd repo
sudo mkdir site.git && cd site.git
sudo git init --bare

You may also need to chown this directory to the user you will be logging in as through SSH.

Setup the Git Hook

Within Git repositories there’s a folder called hooks. We’ll need to cd into that directory and create a new file called post-receive.

cd hooks
sudo nano post-receive

Next we’ll add the working tree to the Git repo. I’m using a Bash shell script because . You may want use #!/bin/sh. More importantly, we are setting the working tree to the folder where our live site will reside.

#!/bin/bash -l
git --work-tree=/var/www/site.com --git-dir=/var/repo/site.git checkout -f

Write out the file, then make sure it’s executable by running chmod +x post-receive. You can exit your server now while we a live remote.

Adding a Live Remote

Presumably, you have a Git repo on your local machine. So, now we need to add the a live remote to push changes to. Open your project in a terminal window and add the git remote like so:

git remote add live ssh://user@mydomain.com/var/repo/site.git

Then, once you’re ready to push up your repo to the live server, run the following command:

git push live master

Ya Donezo!

In conclusion, you should now be able to push new changes to your live server from your local machine. Additionally, you could setup your post-receive to run Grunt tasks like compile sass and whatnot to further automate deploying.