How to setup remote website deployment using git the proper way

Years ago I set this up with a bunch of convoluted scripts, and etc. No fun.

Today I did a bit of research and found out how to easily setup your web server to pull updates from your git repo anytime you publish to it – the proper way.

Here’s how to do it.

First, connect to your remote web server

ssh youruser@yourserver.com

Note, we make some assumptions that you host your site in /var/www/html and that you’ve already added your ssh keys to your git server for both master, and production web server.

Next you’re going to want to issue the following commands

cd /var/www
git init --bare /var/www/theproject.git 
cd theproject.git/hooks/
nano post-receive 

Then you’re going to want to paste this in, shamelessly stolen from this site.

#!/bin/bash
TARGET="/var/www/html"
GIT_DIR="/var/www/theproject.git"
BRANCH="master"

while read oldrev newrev ref
do
    # only checking out the master (or whatever branch you would like to deploy)
    if [ "$ref" = "refs/heads/$BRANCH" ];
    then
        echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
        git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
    else
        echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
    fi
done

Edit the TARGET, and GIT_DIR then save and exit the file, and then make it executable.

chmod +x post-receive 

Now you’re ready to test it all out.

Go back to your development machine (laptop, whatever) and issue the following commands.

cd /path/to/git/repo
git remote add production user@yourserver.com:/var/www/theproject.git

Note, you need to edit the username, server, and project name and path that coincide with your settings, and, whatever has a shared ssh key with your git server.

Now you just need to commit your changes, and then push to master and to production and you’re done!

cd /path/to/git/repo
echo "test" >> index.html 
git add -A . 
git commit -m "adding test html"
git push origin master
git push production master

Refresh your website and you should see the changes!

No comment yet, add your voice below!


Add a Comment

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

Comment *
Name *
Email *
Website