GitDeployRepositories6 min read

Install and use Git on the server

Install Git, create bare repositories, and configure hooks for automatic deployment.


Git on the server lets you receive code directly and execute automatic deploys with hooks.

Step 1 — Install Git

bash
sudo apt update
sudo apt install git -y
git --version

Step 2 — Create a bare repository

A bare repository has no working directory, it only receives pushes:

bash
mkdir -p /home/deploy/repos/myapp.git
cd /home/deploy/repos/myapp.git
git init --bare

Step 3 — Configure post-receive hook

This hook runs every time you push to the server:

bash
nano /home/deploy/repos/myapp.git/hooks/post-receive

Content:

bash
#!/bin/bash
TARGET="/var/www/myapp"
GIT_DIR="/home/deploy/repos/myapp.git"
BRANCH="main"

while read oldrev newrev ref
do
  if [ "$ref" = "refs/heads/$BRANCH" ]; then
    echo "Deploying branch $BRANCH..."
    git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
    cd $TARGET
    # Post-deploy commands
    echo "Deploy completed: $(date)"
  fi
done

Set permissions:

bash
chmod +x /home/deploy/repos/myapp.git/hooks/post-receive

Step 4 — Prepare destination directory

bash
sudo mkdir -p /var/www/myapp
sudo chown deploy:deploy /var/www/myapp

Step 5 — Configure remote on your local machine

bash
cd ~/my-project
git remote add production deploy@YOUR_IP:/home/deploy/repos/myapp.git

Step 6 — Deploy

bash
git push production main

The hook runs automatically and deploys the code.

Step 7 — Advanced hook with service restart

bash
#!/bin/bash
TARGET="/var/www/myapp"
GIT_DIR="/home/deploy/repos/myapp.git"
BRANCH="main"

while read oldrev newrev ref
do
  if [ "$ref" = "refs/heads/$BRANCH" ]; then
    echo "Deploying..."
    git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
    cd $TARGET
    npm install --production
    npm run build
    sudo systemctl restart myapp
    echo "Deploy OK: $(date)"
  fi
done

View deploy history

bash
cd /home/deploy/repos/myapp.git
git log --oneline -10

With Git on your Baires Host VPS, you have a simple and controlled deploy flow without depending on external services.


Was this guide helpful?