How to set up a git bare repository for web development code pushes

30 Dec 17 20:00
2 minutes read

Hi all, let’s consider that you already have your nice local development environment in which you develop your projects. At some point you’ll want to get to get that project on a public server to share with friends, clients or maybe customers. And of course, since you’re using a version control, you want an easy way of pushing updates to that server.

An easy way to do this, is set up a git bare repo on your server. For a great explanation of the differences you can check out this article.

Now that we have that sorted out, let’s get to business. Let’s consider that our public folder is at /home/~username/public where ~username is a system user. What I’m usually doing is firstly setting up my public key as a way of getting on the server.

mkdir .ssh
chmod 700 .ssh
touch .ssh/authorized_keys
chmod 644 .ssh/authorized_keys

Now use vim or your preferred editor to add the public key as a one liner in authorized_keys.

Next step is to initiate our git bare repository. By personal convention I’m creating a .gitrepo folder so feel free to use something else if it suits your better. The only constraint is important to have is to not create it in the public folder.

mkdir .gitrepo
cd .gitrepo/
git init --bare
cd hooks/
touch post-receive
chmod +x post-receive

Now it’s a matter of writing a small shell script of doing the work.

We have two options for setting up the checkout.

  1. Checking out only a specific branch
GIT_WORK_TREE=../ git checkout -f [branch]
  1. Checking out any branch (this is useful for a development setup)
while read oldrev newrev refdo
    branch=┬┤echo $ref | cut -d/ -f3┬┤
    GIT_WORK_TREE=../ git checkout -f $branch

Since we have the post-receive hook setup, we can also run any other shell commands that are needed for example compiling our web assets or installing required dependencies.

Once that’s done, you can use the remote repository after you add it to your local git repository using the following command:

git remote add [remote-name] ssh://[~username]@[site|ip]/~/.gitrepo

« Back to posts