使用php部署工具deployer实现自动部署
利用git webhook请求php脚本,触发deployer自动部署实现的核心流程:PC/Client(git push) => GitHub/Git Repository(webhook/http request) => Server/WebHost(php hook/shell_exec) => Server/WeHost(deploy commands)
设置部署公钥
部署脚本执行的用户www-data
,把www-data
的公钥添加到仓库的部署公钥里以便ssh访问git更新代码。
Deployer部署配置
安装deployer
配置deployer
生成配置文件
dep init
详细参考Deployer文档 - 配置
<?php
namespace Deployer;
require 'recipe/laravel.php';
// Configuration
set('ssh_type', 'native');
set('ssh_multiplexing', true);
set('repository', 'git@git.oschina.net:maoxuner/pandora.git');
set('branch', 'geeka');
add('shared_files', []);
add('shared_dirs', []);
add('writable_dirs', []);
// Servers
localServer('sunny', 'localhost')
->set('deploy_path', '/var/www/geeka')
->pty(true);
// Tasks
desc('Set Environment');
task('setEnv', function () {
run("cp {{deploy_path}}/release/.env.testing {{deploy_path}}/release/.env");
run("php {{deploy_path}}/release/artisan key:generate");
});
after('deploy:vendors', 'setEnv');
// [Optional] if deploy fails automatically unlock.
after('deploy:failed', 'deploy:unlock');
// Migrate database before symlink new release.
before('deploy:symlink', 'artisan:migrate');
WebHooks
不同Git仓库,webhook发送的数据不同,这里以Git@OSC为例。
php脚本
www-data
对目录应具有写入权限,否则得注释日志记录的相关代码。建议把该文件放在根目录以外的目录,并配置别名,这样自动部署的时候不会影响到该文件。
<?php
$password = 'hook password'; // 钩子密码,用来防止恶意访问
$branch = 'master'; // 部署分支,用来过滤其他分支的推送消息
$postStr = file_get_contents("php://input");
$fh = fopen('deploy.log', 'a');
fwrite($fh, $postStr."\n");
$data = json_decode($postStr);
if($data && property_exists($data, 'password')){
if($data->password == $password && $data->ref == 'refs/heads/'.$branch){
$result = shell_exec('dep deploy');
fwrite($fh, $result."\n");
}
}
fwrite($fh, date('Y-m-d H:i:s')."\n-------- 分 -- 割 -- 线 --------\n\n");
fclose($fh);
Git仓库设置
添加一个webhook,URL地址为以上php脚本的地址,并设置好密码。
利用git hook自动部署
目测是以WebHost作为git仓库,并通过仓库本身来执行shell脚本,实现自动部署。参考使用 Git Hook 实现网站的自动部署
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南