AUTO_DEPLOY.md 3.0 KB

自动部署配置指南

架构说明

Git Push → Gogs Webhook → 服务器 Webhook 接收器 → 自动部署脚本 → PM2 重启

服务器端配置

1. 上传 webhook 脚本到服务器

# 上传到服务器
scp -P 22622 server/webhook-deploy.py root@8.159.134.106:/data/ai/

# 或者直接编辑服务器上的文件
ssh -p 22622 root@8.159.134.106

2. 设置 webhook 服务自启动

创建 systemd 服务文件 /etc/systemd/system/webhook.service:

[Unit]
Description=Webhook Deploy Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/data/ai
Environment=WEBHOOK_SECRET=your-secret-key
Environment=WEBHOOK_PORT=8080
ExecStart=/usr/bin/python3 /data/ai/webhook-deploy.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

启用服务:

systemctl enable webhook
systemctl start webhook
systemctl status webhook

3. 配置 Nginx 转发

在 Nginx 配置中添加:

location /webhook {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
}

重载 Nginx:

nginx -t && nginx -s reload

Gogs Webhook 配置

  1. 登录 Gogs 进入仓库
  2. 设置 → Webhook → 添加 Webhook
  3. 选择 "Gogs"
  4. 填写:
    • URL: https://book.rrbrr.com/webhook?secret=your-secret-key
    • Secret: your-secret-key (与脚本中设置的一致)
    • 触发条件: 选择 "Push" 事件
  5. 点击"测试"验证连接

安全建议

  1. 使用 HTTPS: 确保域名已配置 SSL 证书
  2. 设置强 Secret: 不要使用默认的 your-secret-key-change-me
  3. 限制 IP: 可以在 Nginx 中限制只有 Gogs 服务器 IP 可以访问 /webhook
  4. 日志监控: 定期检查 /tmp/webhook-deploy.log

手动触发部署

# SSH 到服务器
ssh -p 22622 root@8.159.134.106

# 手动执行部署
cd /data/ai
bash deploy-auto.sh

故障排查

# 查看 webhook 服务状态
systemctl status webhook

# 查看 webhook 日志
tail -f /tmp/webhook-deploy.log

# 查看 PM2 日志
pm2 logs server

# 测试 webhook 端点
curl -X POST https://book.rrbrr.com/webhook -d "test=1"

简化版(无需 Python)

如果服务器没有 Python,也可以用纯 bash + Nginx + Git Hook:

创建 Git Post-Receive Hook

在服务器的 Git 仓库中创建 hooks/post-receive:

#!/bin/bash
while read oldrev newrev refname; do
    branch=$(echo $refname | cut -d/ -f3)
    if [ "$branch" = "master" ]; then
        echo "Detected push to master, deploying..."
        cd /data/ai/audio_codebuddy
        git pull origin master
        cd /data/ai/audio_codebuddy/server
        npm run build
        pm2 restart server
        echo "Deploy completed at $(date)" >> /tmp/deploy.log
    fi
done
chmod +x /data/ai/audio_codebuddy/.git/hooks/post-receive

注意: 这种方式需要 Gogs 使用服务器的本地 Git 仓库路径,而不是 HTTP/HTTPS 克隆 URL。