Deploying with Git

I’ve been using my own bash shell scripts to deploy my projects, but this can be too much overkill. After doing some research, I found ( http://gitolite.com/deploy.html ). Which lead me to experiment and found it quiet useful!

  1. This is what I have:

    I work locally and my main repository is hosted by Bitbucket I’ve got two remote servers, for staging and a production I use public keys to access my servers by ssh, no password typing needed (http://www.debian-administration.org/article/SSH_with_authentication_key_instead_of_password)

  2. What I’d like to do:

    I want to run commands like (to deploy) :

git push staging branchName

and

git push production branchName

to deploy!

  1. This is how to do it:

    Assuming you’ve got your local development environment and repository already setup. In my case I’m using Bitbucket, but you may use your local, github or any other! You can see what remote locations you already got by running “git remote -v”

    Connect to your remote server, let’s call it production server (could be staging, for example)

    Create a new –bare remote repository. Bare means that will only contain the version controlled files and no .git configuration files, etc (http://gitready.com/advanced/2009/02/01/push-to-only-bare-repositories.html).

Do as follow:

cd /var/www/myProject/

mkdir production.git && cd production.git

git init --bare
Edit the /var/www/myProject/production.git/hooks/post-receive file and add the following:
GIT_WORK_TREE=/var/www/myProject git checkout -f
The GITWORKTREE tells the location where to run "git checkout -f" and what this does is forcing git to overwrite files if neeed, etc. You can also provide the branch you want to checkout, for example, let's say: git checkout -f staging. Why ? Let's say branch master is reserved for production and staging that's where you merge all your tests and work not approved to production. Here you'd push by: git push staging staging; Makes sense ?

Then make sure you have the right permissions to execute the file:
chmod +x /var/www/myProject/production.git/hooks/post-receive

This basically means that whenever you push from your local to the remote “production”, the post-receive hook is executed!

To finish, you need to setup this “production” repository to your local configuration file, he needs to know this exists, you need to tell him the location, like:

git remote add production ssh://username@myRemoteServer/var/www/myProject/production.git

Push the initial files there by:

git push production +master:refs/head/master

At this point you should have all the files, in the remote “production” repository. Every time you want to send new stuff, just do:

git push production branchNameGoesHere

That’s all!

comments powered by Disqus