Auto Deploy Your Code With Git!

On an assignment recently, I worked with a dev-ops team that refused to have anything to do with FTP, and rightly can be a very inefficient and insecure way to transfer files.

When I asked “well, how do I get the code to the server then?” I was told it was all done behind the scenes when I commit to git. I was intrigued and wanted to do that for my personal projects …and this is how I did it.

First I log into my production server (really, this can be set up for any type of server), and create a folder outside of where the public folder lives that will be our target for commits. We create a ‘bare’ repository

git init --bare ~/project.git

Then create the script to be executed when it receives a commit..this is called a ‘hook’
and will live here: project.git/hooks/


while read oldrev newrev ref
	# only checking out the master (or whatever branch you would like to deploy)
	if [[ $ref = refs/heads/$BRANCH ]];
		echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
		git --work-tree=$TRAGET --git-dir=$GIT_DIR checkout -f
		echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."

Now we’re ready to set up things locally where our code is:

$ cd ~/path/to/working-copy/
$ git remote add production

Now all that’s left to do is to deploy that wonderful code..and profit!

$ git push production master

Less time moving files = more time developing new features!