Auto deploying code to production server with GIT

This is the simple steps where you can follow easily to deploy your script from local working directory to production server.

Normally you are working on your code in your development environment (mostly is your local machine) and manage your version with Git, either in your local machine it self, a self host Git Server or a public Git server such as GitLab or GitHub. To deploy your script to server normally you will need to login to server to pull it from the same source or export it manually to the server.

The following step is an alternative solution where you can host a “bare” git repository in your production server and automate the publication step when you push your latest script to the particular branch in your server (basically your master branch) with “Hook”. By doing that you actually can skip the middle man to help to deploy the script.

For the demonstration purpose, my environment detail as per following:

– Ubuntu 16.04

– GIT installed

– NGinx installed

– PHP 7.0 FPM installed

To follow the step, you need to have a basic knowledge on the following:

– Know how to use GIT

– Know how to use Terminal

– Have a local working copy ready

– Have SSH access to your server using public, private key

The summary of the complete procuess:

– Create a folder to deploy on production server (i.e. your httpds folder)

– Create a folder for bare repository on the productions server

– Initialize a bare repository on the productions server

– Add the post-receive hook script to the bare repository (and make it executable)

– Add the remote-repository resided on the production server to your local repository

– Push to the production server, relax.

Just follow the simple step as following:

1. Create a folder for production script /var/www/domain.com

cd /var/www/

sudo mkdir domain.com

2. Create a git repo /var/repo/domain.com.git

cd /var/

sudo mkdir repo

cd repo

sudo mkdir domain.com.git

3. Create a bare repository to store the versioning, it’s does not contain any working copy files, it’s only contain of .git repository

git init –bare /var/repo/domain.com.git

4. Edit the hook

This script is executed when the push from the local machine has been completed and moves the files into place. It resides in domain.com.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)