Using Git as a deployment mechanism

When you’re working with a database that is shared between your live and development environments, you need a way to access that database. With my set up, this involves either SSH tunnelling to the server or executing the dev and live code directly on the server. The first option almost always ends up in code changes that won’t be used in production, so this method isn’t preferred. I therefore execute both development and production code on the same server.

Development became pretty unproductive when I needed to keep uploading a revised version of my code every 5 minutes, so I began to use Git. With this, I could make regular commits as I was developing, then pull the latest code in one command on the server. With PHP in particular, I like to keep running code to see how it’s progressing, or even adding small print statements to try to debug something. Executing this same `git pull` command every time became tedious, and I read up about Git hooks that can be used to notify a git server when some new code has been pushed up. This wasn’t exactly what I wanted because it involved having a complete copy of the git server on my production server. Since I use Bitbucket to store code, I found they have a service called ‘WebHooks’ – this lets you make an HTTP request to any endpoint you like, every time some code is pushed to your repository.

I created a simple PHP script that executed the `git pull` command on the server, and pointed BitBucket to it – and this is how my development process sped up. Once I’ve finished my mini development “sprint”, I now commit my code and in less than a second my server knows about it, and runs the latest code. I then took this a step further.

Confession: I used to do my development in the production environment.

Yep. Bad practice, I know.

But now, I have two branches set up in Git – one Master and one Dev. These all get pushed to the Bitbucket repository, but I ensure that code in the Dev branch is working correctly on the Stage environment before merging into the Master. This means I never break the production environment, and whilst I develop a client application for the server, I can be using the Stage server.

For those interested, the PHP script is simply:

// Stage
echo exec('cd /home/stage/path/to/git/dir && git pull origin dev');
// Production
echo exec('cd /home/production/path/to/git/dir && git pull origin master');

Leave a Reply

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