raw.githack.com

Auto-deploy on push to remote Set up automatic deployment for your pet projects with post-receive hooks

Tired of manually deploying your pet projects after every push? Want to see your changes live immediately without setting up complex CI/CD? Git’s post-receive hooks can give you instant deployment. We’ve covered git hooks in detail in a separate post, so this article builds on that knowledge.

This approach is perfect for personal projects, prototypes, or simple websites. It’s not a replacement for proper CI/CD systems like Jenkins or GitHub Actions, but rather a quick way to get continuous deployment working with minimal setup.

Let’s start by setting up your project repository on the server. This will be your main repository where you’ll deploy from:

git init ~/git-repos/my-website
cd ~/git-repos/my-website
git config receive.denyCurrentBranch updateInstead

The updateInstead setting is crucial here - it allows pushes to the current branch and automatically updates the working directory with new changes. Without this, Git would reject pushes to prevent accidentally overwriting your working files, but since we want automatic deployment, we need this behavior.

The magic happens in the post-receive hook. This script runs every time someone pushes to the repository:

#!/bin/bash
# ~/git-repos/my-website/.git/hooks/post-receive

while read oldrev newrev refname; do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)

    if [ "$branch" = "main" ]; then
        # Change to repository root (hook runs from .git directory)
        cd ..

        # Build and restart
        make build
        make restart
    fi
done

Make the hook executable:

chmod +x .git/hooks/post-receive

Now, from your local machine, clone the repository and set up your project:

git clone user@your-server:~/git-repos/my-website
cd my-website
# Add your files, commit, and push
git add .
git commit -m "Initial website"
git push origin main

You can also organize your workflow with separate remotes. Keep your code in a regular repository (like GitHub) and add a deploy remote:

# Add your main repository
git remote add origin https://github.com/username/my-website.git

# Add deploy remote
git remote add deploy user@your-server:~/git-repos/my-website

# Push code to main repo
git push origin main

# Deploy when ready
git push deploy main

Every time you push to the main branch, the post-receive hook will automatically update the working directory and run any necessary build steps. Your website will be updated instantly!

This setup is perfect for static websites, simple web apps, or any project where you want instant deployment without the overhead of a full CI/CD pipeline. Just remember that this is a quick solution for pet projects, not enterprise-grade deployment.

Happy hacking!