Git: Pushing and Deploying to a Private Server

July 06, 2017

Git Deployment Tutorial
SSH Key Setup

Context
I needed to push to deploy my scraping app to a server. Using git seems to be the way to deploy web apps, so thought to use the same method.

Locations

There are four locations to keep in mind. I’m deploying to an Ubuntu Server 16.04.

Location A is self-explanatory. It contains all the working code and is a git repository on your laptop.

Location B is a bare git repository. It only contains the git metadata references, not the working code on a remote server (Ubuntu 16.04 in this case).

Location C is where the working code goes. In this case, it’s on the same server as Location B.

Location D is an optional, but recommended, place to store all changes to your code.

Location A

On this machine, you’ll make your project space, and add the remote repos, C and D.

$ mkdir /Users/dhruvkar/projects/mysuperproject
$ cd /Users/dhruvkar/projects/mysuperproject
$ git init
$ git remote add live ssh://dhruv@<ipaddress_of_server>/home/gitrepos/mysuperproject.git    #add private server as remote (Location C)
$ git remote add origin https://github.com/dhruvkar/mysuperproject.git                      #add github as remote (Location D)

Note that you’ll have to setup ssh keys with each of the remotes.

Location B
$ ssh remoteserver                              #login to your remote private server
$ mkdir -p /home/gitrepos/mysuperproject.git    #create bare git repo
$ cd /home/gitrepos/mysuperproject.git          
$ git init --bare                               #initialize git

This will create a bunch of directory including a hooks directory.
In this directory we’ll create a post-receive hook that’ll handle receiving a push from our local repo.
While in the bare git repo do, vim hooks/post-receive. The contents of the hook are as follows:

#!/bin/sh
git --work-tree=/home/production/mysuperproject --git-dir=/home/gitrepos/mysuperproject.git checkout -f

Make this file executable: chmod +x hooks/post-receive

The work-tree is Location C, while the git-dir is Location B.

Location C

On the same machine as Location B: $ mkdir -p /home/production/mysuperproject/

The post-receive hook we created above will receive a git push to Location B (from Location A) and then pull all the working code into Location C.

Location D

This is the Github repo. If you’ve setup the SSH keys correctly and added this repo as a remote in Location A, you should be able to push to it from the your local repo.

Conclusion

Now the workflow looks like this:

# Do this at Location A

$ git add .
$ git commit -m "first commit"
$ git push -u origin master         #push to Github
$ git push live master              #push to remote private server

You should now see your local repo reflected in Locations C and D.