Linux Tips guides, explanations and reader checklists on whilenetworking.com

How to Install and Configure a Private Git Repository on Your Linux Machine

In today's distributed development environment, relying solely on public repositories like GitHub or GitLab is often insufficient for sensitive projects,…

In today’s distributed development environment, relying solely on public repositories like GitHub or GitLab is often insufficient for sensitive projects, proprietary codebases, or internal tools where data privacy and access control are paramount. Setting up a private Git server on your own Linux machine offers complete control over your source code, eliminates external downtime risks, and ensures that your intellectual property remains within your network perimeter. This guide provides a step-by-step approach to installing and configuring a robust private Git repository using the industry-standard git-hosting tools or by leveraging existing packages like git-http-backend combined with a web server.

By following this tutorial, you will learn how to secure your installation, configure access controls, and set up a seamless workflow for your development team. We will cover everything from initial package installation to creating the first repository and managing user permissions. Please note that while these instructions are designed for Linux systems, specific commands may vary slightly depending on your distribution (e.g., Debian/Ubuntu vs. RHEL/CentOS). Always verify prerequisites and paths against your specific OS version before executing commands.

Prerequisites and Environment Setup

Before installing the Git server software, it is essential to prepare the environment. You will need a Linux machine with root or sudo privileges. While modern distributions come with Git pre-installed, ensuring the latest version is available is recommended for security and feature support.

First, update your package index to ensure you are pulling the most recent definitions:

sudo apt update && sudo apt upgrade -y

Next, install the core Git components. On Debian-based systems like Ubuntu or Mint, run:

sudo apt install git git-http-backend

For RHEL-based systems like CentOS or Rocky Linux, use:

sudo yum install git-server gitweb

or for newer versions using DNF:

sudo dnf install git-server gitweb

If you plan to host the repository over HTTPS (recommended for production), you will need OpenSSL and a web server like Nginx or Apache. For this guide, we will focus on the core Git installation first, then layer in the web server configuration later. Ensure your firewall allows traffic on port 22 (for SSH) or port 80/443 (for HTTP/HTTPS).

Configuring Global Git Settings for the Server

Once the software is installed, you must configure the Git daemon to handle requests correctly. The default installation often lacks the necessary hooks and configuration files required for a secure server environment.

Create the main Git directory structure. It is best practice to place the repositories in a dedicated directory rather than your home folder:

sudo mkdir -p /srv/git/repositories
sudo chown git:git /srv/git/repositories

Note: You may need to create a git user if it does not exist, or use your existing system user with appropriate permissions.

Configure the Git daemon settings by editing /etc/git/config. This file dictates how the server handles incoming connections, authentication methods, and allowed protocols. Ensure that only trusted networks can access the repository. You should explicitly define which projects are accessible:

sudo nano /etc/git/config

Add lines specifying your repositories:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
[userX]
    email = admin@example.com
    name = Git Administrator
[receive.denyCurrentBranch]
    updateInstead = true
[receive.denyDeleteEmpty]
    true

Securing the Repository with SSH and HTTPS

Security is the most critical aspect of a private repository. You have two primary protocols to configure: SSH and HTTPS. SSH is generally preferred for internal networks as it does not require managing SSL certificates for every clone operation, though HTTPS offers better integration with web-based CI/CD pipelines.

Setting Up SSH Access

Generate an SSH key pair if you haven’t already, or ensure the git user has a valid .ssh directory:

sudo -u git ssh-keygen -t ed25519 -f /home/git/.ssh/id_rsa
sudo chmod 700 /home/git/.ssh
sudo chown -R git:git /home/git/.ssh

Edit the SSH configuration file at /etc/ssh/sshd_config to ensure PubkeyAuthentication yes is set. Restart the SSH service after changes:

sudo systemctl restart sshd

Configuring HTTPS Access

To allow cloning over HTTP, you need to install a web server. Using Nginx as an example, install it and configure a reverse proxy to pass requests to the Git daemon:

sudo apt install nginx git-http-backend

Create a new site configuration file at /etc/nginx/sites-available/git-repo:

server {
    listen 80;
    server_name your-domain-or-ip;

    location / {
        include git-http-daemon.sh default /srv/git/repositories;
    }
}

Enable the site and restart Nginx:

sudo ln -s /etc/nginx/sites-available/git-repo /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Creating Your First Private Repository

With the infrastructure in place, you can now create a repository. The process differs slightly depending on whether you are cloning an existing remote repo or initializing a new bare repository directly on the server.

To initialize a new bare repository (which is the standard for servers), navigate to your repositories directory and run:

cd /srv/git/repositories
sudo git init --bare my-private-project.git

This creates a special Git database without a working tree, ready to accept pushes from developers.

Next, allow specific users or groups to push to this repository. You can restrict access by creating an .git/config file inside the bare repo or by using ACLs (Access Control Lists) on the filesystem. A common method is to create a group for your developers:

sudo usermod -aG git $DEVELOPER_USERNAME

Then, set permissions on the repository folder so only members of the git group can write:

sudo chown -R git:git /srv/git/repositories/my-private-project.git
sudo chmod -R 750 /srv/git/repositories/my-private-project.git

Managing User Permissions and Access Control

A private repository is only useful if you can control who accesses it. Misconfigured permissions are a common source of data breaches. You should implement a tiered permission system: administrators can push and delete, while developers can only pull and push to specific branches.

Use Git hooks to enforce additional logic. For example, create a post-receive hook in the bare repository to log every commit or restrict branch creation:

cd /srv/git/repositories/my-private-project.git
sudo nano .git/hooks/post-receive

Inside this file, you can write shell scripts that check environment variables or group memberships before allowing a push. Remember to make the hook executable:

sudo chmod +x .git/hooks/post-receive

Regularly audit your logs located in /var/log/git (if configured) or via the web server logs to detect unauthorized access attempts. Rotate these logs periodically to prevent disk space exhaustion.

Real-World Example and Troubleshooting Checklist

Consider a scenario where a small engineering team wants to move their internal dashboard code to a private server. They follow these steps:
1. Install Git and Nginx on a dedicated Ubuntu 22.04 LTS machine.
2. Create the /srv/git/repositories directory owned by the git user.
3. Initialize a bare repo for their project.
4. Configure Nginx to serve the repository at http://internal-git.company.local/project.git.
5. Add three developers to the git group and configure SSH keys for each.

Common Mistakes to Avoid:
* Ignoring SSL: Never expose a private repo on port 80 without HTTPS in a production environment; unencrypted traffic can be intercepted.
* World-Writable Directories: Ensure /srv/git/repositories is never set to 777. This allows any user on the system to push code, bypassing authentication.
* Hardcoding Credentials: Do not store passwords in scripts or configuration files; use SSH keys or environment variables instead.

Troubleshooting Checklist:
* [ ] Can you clone from a local machine? (git clone http://server/repo.git)
* [ ] Does the post-receive hook execute without errors?
* [ ] Are log files showing successful authentication attempts?
* [ ] Is the Nginx configuration syntax valid? (nginx -t)

Conclusion

Setting up a private Git repository on a Linux machine empowers your organization to maintain strict control over its codebase while ensuring high availability and security. By carefully configuring SSH and HTTPS access, managing user groups, and implementing hooks for automated validation, you create a resilient infrastructure that supports collaborative development without exposing sensitive data to the public internet. Remember that technology evolves rapidly; always check for updated packages and security patches to keep your private repository secure against emerging threats. With the steps outlined above, you now have a functional, secure, and scalable Git hosting solution tailored to your Linux environment.