How to set up Git for automated deployments

1 year ago by Jurjen Smakman

At Diffuse we use Git to version control our code. We also use it to deploy our websites and applications. In this post I'll walk you through the steps to set up Git for automated deployments.

Creating a remote Git repository

Like Github or Gitlab your staging and production server can serve as remotes for your code. To set this up you first need to create a git repository on your remote server. Login to your server using Terminal for example:


Then create a bare git repository:

 cd /home
mkdir repos && cd $_
mkdir production.git && cd $_
git init --bare

In this example I use /home/repos/production.git as the reposity directory and /home/www/ as the webroot. You'll probably have to adjust these paths to correspond with the setup of your server.

Set up a Git post-receive hook

After initialising the repository we will create a post-receive hook which is run after each push:

 cat > hooks/post-receive

In this script we will tell Git to copy the code from the repository to the webroot:

git --work-tree=/home/www/ --git-dir=/home/repos/production.git checkout -f

In the post-receive hook you can run any additional shell commands. We clear out the caching folders for example after each push. When you are finished setting up your post-receive hook save the file (CTRL+D) and set the proper permissions with:

 chmod +x hooks/post-receive

After that you're done on the remote server and you can close the connection with exit.

Local setup

On your locale machine cd into your project folder and init git if you haven't already with git init. After that add the repository we've just created on the server as a remote with:

 git remote add production

Now you are al set up to push code to push into production:

 git add .
git commit -m "Ready for production"
git push production master

That's it! You've just pushed code into production. In the same way you can set up a remote repository for you staging environment too.