Continuous Integration is essential when developing restful api’s and testing webhooks. You are developing in a working-copy on your local machine, lets say on the master branch. Most of the time, people would push code to a remote server like github.com or gitlab.com and pull or export it to a production server. With this approach, your pushed brached will auto-pull on the remote server.

Prerequisit

  1. Know how to use GITs, Terminal etc.
  2. Have a local working-working copy ready
  3. Have SSH access to your server using private/public key

1. Have a local working-working copy ready

Assuming we are working on master branch – but you could work on any branch.

2. Create a folder to deploy to

ssh into your remote server:

$ ssh user@server.com
$ mkdir ~/deploy-folder

3. Add a bare repository on the production server

Now we create a “bare” repository – one that does not contain the working copy files. It basicaly is the content of the .git repository folder in a normal working copy. Name it whatever you like, you can also ommit the .git part from project.git or leave it to create the repository in an exisiting empty folder:

$ git init --bare ~/project.git

4. Add the post-receive hook

This scrtipt is executed when the push from the local machine has been completed and moves the files into place. It recides in project.git/hooks/ and is named ‘post-receive’. You can use vim to edit and create it. The script does check if the correct branch is pushed (not deploying a develop branch for example) and

#!/bin/bash

target_branch="production"
working_tree="PATH_TO_DEPLOY"

while read oldrev newrev refname
do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ -n "$branch" ] && [ "$target_branch" == "$branch" ]; then
    
       GIT_WORK_TREE=$working_tree git checkout $target_branch -f
       NOW=$(date +"%Y%m%d-%H%M")
       git tag release_$NOW $target_branch
    
       echo "   /==============================="
       echo "   | DEPLOYMENT COMPLETED"
       echo "   | Target branch: $target_branch"
       echo "   | Target folder: $working_tree"
       echo "   | Tag name     : release_$NOW"
       echo "   \=============================="
    fi
done

5. Add remote-repository localy

Now we add the this bare repository to your local system as a remote. Where “production” is the name you want to give the remote. This also be called “staging” or “live” or “test” etc if you want to deploy to a different system or multiple systems.

$ cd ~/path/to/working-copy/
$ git remote add test_server demo@yourserver.com:project.git

Make sure “project.git” coresponds to the name you gave in step 3. If you are using Tower or a similar App, you will see the newly added remote in your sidebar under “Remotes” (make sure it’s not collapsed).

6. Push to the server

Now you can push the branch to the server:

$ git push test_server local_branch:remote_branch