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:
git init --bare your_project.git# ormkdir your_project.gitcd your_project.gitgit init --bareAfter initialization, /root/project/your_project.git will contain the following:
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 └── tags2. 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 nginxDeployPath="/data/www/xxxx.com"
cd $DeployPath
git pull origin masterGive post-receive execute permission:
chmod +x post-receive3. 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.
# Run this command in your local repositorygit remote add origin root@192.168.1.1:/root/project/your_project.git# Pushgit push origin masterNote: 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.