点击上方“蓝字”,发现更多精彩。
END
扫码关注我们
微信号:gh_dcd05cdf3c3e扫码关注我们,获取最新资讯。分享,点赞,在看,都在这儿,点我不香吗?
很抱歉网站傍晚岩机3个多小时。因为最近看到有瓜娃子在我面前耍帅,说他的项目都不用手动更新就可以直接上线,只要把代码提交到仓库即可,听到这话你能忍么?我忍不了。。。于是我就用脚趾头想了下,大概猜到其原理无非就是提交到git仓库后触发某个监听机制,如果监听代码有更新,通知线上服务器执行脚本拉取代码,我想大概就做这么件事,事实也正是如此,于是傍晚一直通过博客线上服务器直接捣鼓,导致那么一会儿没完全捣鼓好,就岩机了下,好尴尬。。。下面以github项目来讲解具体怎么实现。
找对对应项目仓库
首先我现在GitHub上创建了一个项目,项目创建之后我们需要对该项目设置(Settings),里面有一选项Webhooks,点击进去
服务器配置
最后我们需要在服务器上创建PHP文件(git-webhook.php,可自定义名称)来接收,我博客后台是php语言所以用php实现,这不是重点,重点你要知道流程。
<?php //git webhook 自动部署脚本$requestBody = file_get_contents("php://input"); //该方法可以接收post传过来的json字符串if (empty($requestBody)) { //判断数据是不是空 die('send fail');}$content = json_decode($requestBody, true); //数据转换//若是主分支且提交数大于0if ($content['ref'] == 'refs/heads/master') { //PHP函数执行git命令 $res = shell_exec('cd /www/wwwroot/wp-content/themes/Art_Blog/ && git reset --hard origin/master && git clean -f && git pull 2>&1 && git checkout master'); $file = '/www/wwwroot/wp-content/themes/Art_Blog/dist'; //旧目录 $newFile = '/www/wwwroot/wp-content/themes/Art_Blog/'; //新目录 file_copy($file, $newFile); $res_log = '-------------------------' . PHP_EOL; $res_log.= ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push' . $res; //将每次拉取信息追加写入到日志里 file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);}function file_copy($src, $dst) { $dir = opendir($src); @mkdir($dst); while (false !== ($file = readdir($dir))) { if (($file != '.') && ($file != '..')) { if (is_dir($src . '/' . $file)) { file_copy($src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir);}
php执行xsell_exec命令没反应?
1、文件权限不够,执行命令 chmod 755 git-webhook.php 无效?执行命令 chmod 777 git-webhook.php
2、在php.ini下进行更改(通过宝塔很容易看到,如下图) ,查找disable_function,去掉exec和xsell_exec,重启php
小结
流程就是,代码仓库向服务器发出指令告诉自己有更新,然后服务器收到指令去拉仓库新的代码,了解流程,再去看任何这类部署,就都是大致相通的。
![0e7b13c064cd14783764775f08bb0e9b.gif](https://img-blog.csdnimg.cn/img_convert/0e7b13c064cd14783764775f08bb0e9b.gif)
![4a6bb5103eab2eb7672805858d674dc2.gif](https://img-blog.csdnimg.cn/img_convert/4a6bb5103eab2eb7672805858d674dc2.gif)
![92a7a8d24f0953431e4aa3c09910ba8d.png](https://img-blog.csdnimg.cn/img_convert/92a7a8d24f0953431e4aa3c09910ba8d.png)
![c5898f34a804c24c4593d80d6993f56b.png](https://img-blog.csdnimg.cn/img_convert/c5898f34a804c24c4593d80d6993f56b.png)