How to create private git server

Github, Bitbucket or Gitlab are common git servers you have heard of. But do you know that you can also create your own git server with just a few lines of commands? Today I'm going to show you how to do that.

In this post, I am assuming that you have your own VPS server which is running Ubuntu. After SSHing to the server, please install git if it has not yet been installed

sudo apt-get install git

When git is ready, cd (change directory) to the location that you want to create the repository. And then, run the following command to create the repository

git init --bare my_project.git

Now, in order to clone this project from your client computer, you have to know the HTTP (HTTPS) or SSH location of your git repository. For example, on Github you often see several options like https://github.com/puma/puma.git or git@github.com:puma/puma.git. In this post I will only demo how to clone via SSH because it is simpler. If you want to clone your private git repository via HTTP, I recommend reading this tutorial here: https://www.kernel.org/pub/software/scm/git/docs/howto/setup-git-server-over-http.html (the basic idea is you need a web server to handle request to port 80 of your server, such as Apache or Nginx)

The first step to clone your repos via SSH is to authorize your SSH key. Check on your local machine to see if you have any SSH created in ~/.ssh folder. If not, please generate new SSH key by following the tutorial here https://help.github.com/articles/generating-ssh-keys/

Next, copy the content of your public key (the file which ends with .pub extension). On the server, create a new file (or modify it if exists) at ~/.ssh/authorized_keys

nano ~/.ssh/authorized_keys

Paste the content of your local public key as a new line into this file. By doing this, you will be authorized by the server and no need to type username or password when doing things via SSH

Finally, clone git repos from server to your local machine, replace placeholders with appropriate value.

git clone username@ipserver:path_to_git_repos

For example, if the location of your private git on server is /home/ubuntu/test.git, username is ubuntu and server domain is example.com, you will run the following command:

git clone ubuntu@example.com:/home/ubuntu/test.git

That's it. You now have a private git server to use.
Happy coding!