Git Push Deployment

Git Push Deployment
30 Jan 2016

Git Push Deployment


Git is the most popular version control system for web and software development, and is a must have in any developers toolkit. Most people use it only for tracking changes in your code, but it can also be used to quickly push changes from your local environment to your staging or production server.

The most basic approach would look something like this

#make changes locally
git add file.txt
git commit -m "changes to project"

#store changes on remote repository
git push origin master

#connect to server
ssh user@domain.com
cd /var/www/public_html

#pull changes down
git pull origin master

But it could be streamlined and simplified.

Barebones Repo

Our first step is to create a remote repo on our server, but we’ll create it as a barebones repo to prevent it from storing all of the project files. Instead, it will just store the actual version control changes from one commit to another.

ssh user@domain.com
mkdir /var/repo/domain.com.git
cd /var/repo/domain.com.git
git init --bare

Now we have a new, blank, remote repository on our server. We can treat it pretty much the same way we would our repo on GitHub or BitBucket. We can push and pull branches to this repo just like any other.

Git Hooks

What we want now, is for the repo to recognize when we push to it, and automatically setup the project files in our site’s root directory. Luckily, Git has some prebuilt hooks that we can tap into to accomplish this.

cd /var/repo/domain.com.git/hooks
touch post-receive
chmod +x post-receive

Using your favorite command line text editor (I prefer vim) you can populate the newly created git hook file “post-receive” with the commands we want to run when a new branch push is received by the repo.

#!/bin/sh
git --work-tree=/var/www/domain.com --git-dir=/var/repo/domain.com.git checkout -f
git --work-tree=/var/www/domain.com --git-dir=/var/repo/domain.com.git submodule update --init

This file checks out the source files into our project root and updates any submodules in our project. Our git push deployment is all set! You could run through the exact same steps to setup the same process for your staging site to quickly deploy your changes through your whole workflow.

Git Push Deployment

All that’s left is to push our changes to our new remote repo and let it handle the quick deployment automatically.

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

git add file.txt
git commit -m "changes to project"
git push live master

Now you can check the site at domain.com and your changes will have been automatically deployed to the document root!

Leave a Reply

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