PHP 分布式部署后 代码自动同步实现

项目架构如下:
在这里插入图片描述

需要更新代码时我们只需要把代码传到主服务器后通过定时任务主服务器自动push 代码到Git服务端,之后其他从服务器则自动从Git云端拉取最新的代码即可

需要用到 expect 软件
安装expect

yum install expect

定时push shell(不要用win编辑器编辑 不然cd 找不到文件)

#!/usr/bin/bash
cd /home/wwwroot/test
git add .
git commit -a -m auto
set timeout 60
/usr/bin/expect <<-EOF
spawn git push ssh://mgit@127.0.0.1/home/gitprojects/test master
expect "*password:"
send "123456\r"
interact
expect eof
EOF

定时pull shell

#!/usr/bin/bash
cd /home/test
#延迟5s 等待push 后在拉取
sleep 5
set timeout 60
/usr/bin/expect <<-EOF
spawn git pull ssh://mgit@127.0.0.1/home/test master
expect "*password:"
send "123456\r"
interact
expect eof
EOF

定时任务 主服务器每分钟执行 push,从服务器每分钟执行pull

* * * * * sh /home/wwwroot/test/git_push.sh
* * * * * sh /home/wwwroot/test_server/git_pull.sh

gitignore 把不需要同步的文件处理掉

application/install.lock
application/upload.lock
/.idea
/runtime
/logs
/data
/uploads/pic_cache
/.htaccess
.htaccess
.project

更新gitignore

git rm -r --cached .
git add .
git commit -m 'update .gitignore'

**注意:
1:编辑shell 不要用win 编辑器,不然cd 容易找不到文件目录
2:git 服务仓库文件夹权限应该归属推送账号,客户端运行项目权限应该归属php所属账号
3:拓容服务器拉下代码时注意项目文件夹权限要归属于php所属用户,不然代码无法创建文件夹,些日志那些
4:拓容服务器的代码不要手动改动,改了最后搞完要还原回去,不然定时pull 会有冲突,pull失败,如果已经被修改则可以手动强制同步远端代码(命令如下)
**

$ git fetch --all
$ git reset --hard origin/master
$ git pull

5:清理.git 文件夹,随着时间推移拓容服务器的 .git 可能越来越大,需要定时清理
1:直接删除.git 文件夹
2:在项目中重新创建git仓库

git init

3:设置远端地址

git remote add origin ssh:xxxx

4:强制同步远端代码

$ git fetch --all
$ git reset --hard origin/master
$ git branch --set-upstream-to=origin/master master
$ git pull
Logo

助力广东及东莞地区开发者,代码托管、在线学习与竞赛、技术交流与分享、资源共享、职业发展,成为松山湖开发者首选的工作与学习平台

更多推荐