Simple Auto-Deployment with Git Hooks

Git

Hooks

In Git, hooks are scripts that are called after specific events are executed.

With hooks, you can customize events that are triggered after certain Git actions (such as git push). For example: when a local repository executes git push to the master branch, the server immediately updates the master branch code into the web directory — this action can be achieved through Git hooks.

Auto-Deployment with Git Hooks

1. Initialize the Remote Repository

Assuming our server is Linux, IP address 192.168.1.1, user root. First, initialize a bare Git repository on the remote server:

/root/project/
git init --bare your_project.git
# or
mkdir your_project.git
cd your_project.git
git init --bare

After initialization, /root/project/your_project.git will contain the following:

Terminal window
your_project.git
├── branches
├── config
├── description
├── HEAD
├── hooks
├── applypatch-msg.sample
├── commit-msg.sample
├── post-receive
├── post-update.sample
├── pre-applypatch.sample
├── pre-commit.sample
├── prepare-commit-msg.sample
├── pre-push.sample
├── pre-rebase.sample
└── update.sample
├── info
└── exclude
├── objects
├── info
└── refs
├── heads
└── master
└── tags

2. Configure Git Hooks

The hook to configure is inside the hooks folder. Create a post-receive text file and add the following content:

#!/bin/sh
unset $(git rev-parse --local-env-vars)
# Deployment path, i.e., the web directory specified by nginx
DeployPath="/data/www/xxxx.com"
cd $DeployPath
git pull origin master

Give post-receive execute permission:

Terminal window
chmod +x post-receive

3. Add Remote Origin to Local Repository

After adding the remote repository source to the local repository, whenever you execute git push to the master branch, it will trigger the Git hook and run the shell script above.

Terminal window
# Run this command in your local repository
git remote add origin root@192.168.1.1:/root/project/your_project.git
# Push
git push origin master

Note: Executing the above command will push all master branch code to the remote server’s repository. If you need to separate branches, set different branch names in the corresponding scripts.

4. Verify Success

Navigate to /data/www/xxxx.com and check if the code matches your local code. If it does — success! If not, check the file attributes and user permissions of post-receive (this won’t be an issue in the example using root).

Final Thoughts

In practice, using Git hooks for auto-deployment is a very simple method, yet remarkably convenient for individuals. It’s a perfect tool for personal blog deployment.