利用git hooks进行自动部署

首先的有一个搭建好的git服务器,在想要自动部署的git库的hook文件中添加自动部署hook,在hook中将DeployDir配置为网站根目录,在网站根目录运行

git clone /usr/gitRepo/web.git

将web文件克隆下来,这样在将更改提交到git仓库的时候,就会自动部署网站。

git的hook机制,当git服务器接到各种事件时触发,这里使用的hook是

post-receive

这个hook在git服务器受到push请求,并且接受完代码提交时触发。

具体代码体现:

在git远端仓库的hooks目录下新建post-receive文件:

#!/bin/sh
IS_BARE=$(git rev-parse --is-bare-repository)
if [ -z "$IS_BARE" ]; then
echo >&2 "fatal: post-receive: IS_NOT_BARE"
exit 1
fi
 
unset GIT_DIR
DeployPath="/var/www/gitRepoHtml"
 
echo "==============================================="
cd $DeployPath
echo "deploying the webapp"
 
git fetch --all
git reset --hard origin/master
 
time=`date`
echo "web server pull at webserver at time: $time."
echo "================================================"

添加文件后,将权限改为755,用户改为git

chmod +755 post-receive
chown git:git post-receive

这样在开发者提交代码的时候,就会自动部署。

可能出现的问题:
当有push上传时,github会回调,但问题是由于回调时用的是apache这个用户名,不是你ssh进去时用的那个用户名,所以你会发现apache这个用户名对于那个目录没有操作权限:

error: cannot open .git/FETCH_HEAD: Permission denied

所以你需要先把ssh_user加到apache组中:

usermod -a -G apache ssh_user

在Apache2中用户组为www-data,ssh_user设置为git

usermod -a -G www-data git	

然后修改权限:

chmod -R g+w /var/www
chown -R git:www-data /var/www
chmod -R g+s /var/www