Deploying websites with a git post-receive hook

I have been looking around for quick and easy ways for deploying website content from our version control system, without having a build process ( the site is ninety nine percent static html and has nothing to build ).  The only aspects that are interesting from a build process is a minifying resources and less compilation.

I have seen a few posts around the web suggesting a git post-receive hook.  The idea of pushing the desired codebase to the desired server is desired, is in fact quite appealing.  I have worked a lot in the past with solutions such as Jenkins, that work great for build solutions, but seemed like overkill for this context.

I use git for the repository management so adding an additional remote is really easy.

Here are the steps that i went through to set this up

Create a user on the linux server specifically for this

useradd -d /home/website -m websiteuser -s /bin/shell

In the home folder create two folders, one for the website code, and the second to hold the git repository.

inside the git folder initialize the repo like this

git init --bare

Once that is done, create your post-receive hook inside the git_repo/hooks directory

my post-receive hook looks like this

FOLDER=`date +"%Y-%m-%d"`
mkdir -p $GIT_WORK_TREE
git checkout -f

echo "Checking for $WEB_ROOT/$LIVE_LINK"

if [ -h "$WEB_ROOT/$LIVE_LINK" ]; then
echo "removing old live link $WEB_ROOT/$LIVE_LINK"

That is all you need for the hook side. Now i would recommend changing the shell of the user for SSH key based login, meaning, copy your SSH key to the authorized_keys file of the website account, well your key and anyone else you want to authorize to deploy to this server. Once the keys are copied, change the shell of the user to git-shell, to prevent anyone trying to login to that account.

That should be all. Now simply add the remote location

git remote add production_deploy website@host:repo.git
git push production_deploy master

You now have the code deployed. The rest is simply configuring your VirtualHost configuration of your apache or nginx server.

Scan to Donate Bitcoin to Tim
Did you like this?
Tip Tim with Bitcoin

Tim Voet has been in the IT industry since 1997. Tim started his career doing tech support and network administration at a large Pharma company. He then spent the next 12 years doing development, leading and managing development teams, mostly in Java, but also some PHP, and Ruby on Rails. Tim has always hands on, and loves challenges that make most people cringe. When he isn't at work, he's spending as much time as he can with his wife and 3 boys. Life can be a busy time with that many young kids. He is currently open to new consulting opportunities, please feel free to contact him with your project information tim - at - timvoet dot com

Leave a Reply

Your email address will not be published. Required fields are marked *