如何使用Git 钩子自动发布代码至生产环境

平时使用 FTP 覆盖旧文件来更新自己生产环境的代码,即繁琐又容易出错,虽然有发布规范,但用人肉来发布代码,的确是有点落伍,如何解放双手,今天我就尝试使用Git 钩子进行简单的自动化部署。
首先:
git --bare init 初始化一个远程仓库

$ cd /data/repo
$ mkdir testWeb.git
$ cd testWeb.git
$ git --bare init

 

我的web程序需要发布到www 目录下,我在这个目录下pull 远程仓库最新的源码

$ cd /data/www
$ git clone /data/repo/testWeb.git #从远程仓库 clone 出源码

 

最重要的一步:

为远程仓库设置 Hook

$ cd /data/repo/testWeb.git/hooks
$ vi post-receive
在post-receive 文件中填上以下执行脚本
#!/bin/sh
unset GIT_DIR
RepoPath=/data/repo/testWeb.git/hooks
cd $RepoPath
git add . -A && git stash
git pull origin master

并且为 post-receive 添加可执行权限
$chmod +x post-receive

 

最后:

在你的本地仓库添加 remote 源在你原有 Git 项目里面添加一条新的 remote 源, push 到这个源里面,代码就会自动触发上面 post-receive bash 脚本了。

$  git remote add fabu git@serverurlorip:/data/repo/testWeb.git
$  git push fabu master

 

最后将我的web程序配置文件db.conf.php
在.gitignore 忽略不提交

发表评论 / Comment

用心评论~