Deploying to production with GIT

My SCM of choice has been GIT for the past few years. Sadly, I still had to FTP the latest code to production due to corporate policy and other constraints. I have since left the tyranny of a corporate environment and have had the opportunity to innovate existing processes and work with new technologies. This has allowed me to move away from the archaic method of updating production code via FTP and use GIT for the entire process. This article is going to walk you through what I do to make my life easier when deploying code.

On the Production Server

  1. First you will want to have a separate directory to store your GIT repository. I typically put this directory right beside my production directory:
    • mkdir /var/www/project.git
    • cd project.git
  2. We will then initialize the GIT repository inside our new directory:
    • git init --bare
  3. We will need to edit a post-receive hook to tell GIT where our files should go. We also force a checkout, which will get rid of all local changes. Just remember that anything you changed on production won't get saved this way. Whatever you push will overwrite any changes unless you check them in.
    • Edit hooks/post-receive and paste the following lines:
      #!/bin/bash
      GIT_WORK_TREE=/var/www/project git checkout -f
    • Make sure that you enter your correct project directory in place of /var/www/project.
  4. Set the post-receive hook as executable
    • chmod +x hooks/post-receive

On Your Local Machine

  1. Go to the directory where you keep your project and add a remote source:
    • cd /home/sites/project
    • git remote add production ssh://<user>@<server>/var/www/project.git
    • When using a visual tool such as source tree, the url is the same as above. Leave your host type as unknown, but in my experience, it will default to Bitbucket. Don't be concerned about this.
  2. Go ahead and push to the server. Remember this will overwrite everything that you have there, so if you have existing code there, make a backup!
    • git push production master:refs/heads/master
    • The first push is done this way because we have an empty repo on the server side.
    • When using Source Tree, right click on master branch and click "Push to" -> "production"
  3. Once this is setup you can easily push to your production server with ease:
    • git push production master