Using git for deployment on your private server

1/19/2020

When creating a new project I have become a fan of deploying via git and git hooks. I can work locally on my machine and when happy push to my private repo on my server and have the changes immediately show up on live production.

Here is simple step-by-step to set this up. You will need a server you can access the shell via ssh or some other authentication method. I generally use Digital Ocean droplets which I setup with my SSH keys already added.

Once I have the IP of the machine the sequence is generally as follows:

Create the folder for the repo (-p creates the parent folders if they don't exist)

mkdir -p home/git/caudurodev.git

Then I go to the directory and initialise the repo (my servers come with git pre-installed)

cd /home/git/caudurodev.git
git init --bare

Lot's of folders will be created, one of them is your hooks folder which has lot's of examples for ways to hook into your git commits. I will create a post-receive hook which will be fired each time a commit to the master branch is executed.

cd hooks
nano post-receive

Add where you would like your repo files to be save to, once the commit happens successfuly (your public server folder where you serve files from):

#!/bin/bash
git --work-tree=/app --git-dir=/home/git/caudurodev.git checkout -f

Make sure your work-tree folder exists too!

You then need to make this file executable otherwise it will not work

chmod +x post-receive

Done. Your repo is set up and you can now push code to the public folder via git!

To access your repo you will need to use a URL that looks something like this:

git remote add origin ssh://root@46.101.245.224/home/git/caudurodev.git

And that's it. You should now be able to develop locally and when you push to the master branch in origin, you will be able to deploy.