git 自动化 post-receive用法(服务器自动化部署的原理)建议先看post-commit的用法
post-receive 的用法比post-commit用法复杂点 基础知识:git基础 linux基础命令 git remote .git init的用法 ,git远程和本地仓库的区别和联系 ssh连接 非必须知识: 你嫌弃github慢的话你也可以自己集成gitlab或者gitweb 需要的工具:一台安装了git的linux服务器,一台安装了git的电脑 上面的内容请自己goole 或 百度 1.远程连接自己的linux服务器打开终端 一般不直接在root用户下添加.(root的权限太高了,为了服务器的安全) 1.添加git用户:
//添加用户git (输密码的时候记着在其他地方记录下别忘记了)
adduser git
//我这里把密码设置为git了
passwd git
- 把用户添加到用户组
//一:切换到root用户下
su root
//二:添加sudo文件的写权限 (记得w后面有空格)
chmod u+w /etc/sudoers
// 第三步:编辑sudoers文件
vi /etc/sudoers
找到这行 root ALL=(ALL) ALL,在他下面添加xxx ALL=(ALL) ALL (这里的xxx是你的用户名)
治理添加
git ALL=(ALL) ALL
//四:撤销sudoers文件写权限
chmod u-w /etc/sudoers
2 .创建完成后
//切换为git用户
su git
//创建 存储你代码的文件 /data/wwwroot/testDeploy/test目录
sudo mkdir -p /data/wwwroot/testDeploy/test
3.初始化裸仓库
cd /home/git
sudo git init --bare test.git
4.git授权
sudo chown -R git lara.git
5 cd到 你刚才创建的/data/wwwroot/testDeploy/test目录下创建本地仓库
cd /data/wwwroot/testDeploy/test
//(其实就是配置本地git仓库)后面追加的路径是 你刚刚创建的远程仓库路径
git clone /home/git/test.git
- 配置hooks
cd /home/git/test.git/hooks/
sudo vim post-receive
这里贴一个shell脚本示例,具体的用法自己根据自己的实际情况自己添加
#!/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="/data/wwwroot/testDeploy/test"
echo "==============================================
cd $DeployPath
echo "deploying the test "
echo "git"| sudo -S git fetch --all
echo "git"| sudo -S git reset --hard origin/master
time=`date`
echo "数据刷新成功at time: $time."
echo "================================================"
7 .执行shell脚本
sudo chmod +x post-receive
测试一下脚本是否有问题
sudo ./post-receive
这样服务端就搞定了剩下客户端的了
随便新起一个目录如test
cd test
// git clone :clone命令
// git :表示的是服务器用户(如果你没配的话这里是root)
//xxxx.xxx.x.xx: 表示你服务器的IP地址
// /home/git/test.git :表示你上面创建的远程仓库路径
git clone git@xxxx.xxx.x.xx:/home/git/test.git
//随便修改点东西
git add .
git commit -m"test"
git push
这是登录你的服务器到 /data/wwwroot/testDeploy/test 查看 会发现你修改的同步到这里了, 以上就是 post-receive,用来做服务器自动化部署的原理