Hugh's Blog

使用 Git Hooks 自动部署代码

自动化部署代码主要是用 Git Hooks,分别需要在服务器与本地开发环境进行配置。

服务器配置

首先建立一个裸仓库来作为触发钩子,这个仓库是要给本地开发环境提交的

cd ~
mkdir remote
cd remote
git --bare init

建立代码仓库,用来拉取上面的裸仓库代码,这里直接在网站根目录下建立了,然后可以配置网站目录指向

cd /var/www/html
# clone 方式,注意权限
git clone /home/{user}/remote deploy # 最好是绝对路径,如果是使用 ssh 方式的话,会要求输入密码等,这里直接使用路径了
# init 方式,注意权限
mkdir deploy
cd deploy
git init
git remote add origin /home/{user}/remote # 绝对路径
git pull origin master # 这里可能会有 Couldn't find remote ref master 错误,因为在初始化裸仓库的时候没有设置分支,可以先提交代码再拉取

钩子触发,回到裸仓库,编写更新脚本 post-receive,文件没有的话就新建

cd ~/remote/hooks
vim post-receive

脚本内容

#!/bin/sh

unset GIT_DIR

CurrentPath=`pwd`
DeployPath="/var/www/html/deploy"

cd $DeployPath
git pull origin master
# ...

cd $CurrentPath
exit 0

为脚本添加可执行权限 chmod +x post-receive

服务器配置基本完成了。

本地开发环境

其实本地开发并没有什么要配置的,只是需要添加 remote 来提交就行了

git remote add deploy ssh://{user}@{ip_address}:{port:22}/home/{user}/remote # 如果有 ssh 验证的话,yes 就行,注意裸仓库路径
git push deploy master

参考

What are Git hooks?

用 Git Hooks 进行自动部署

使用 Git Hook 实现网站的自动部署