方案一:GitHub Actions 自动部署

# .github/workflows/deploy.yml
name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Deploy via rsync
        uses: easingthemes/ssh-deploy@main
        with:
          SSH_PRIVATE_KEY: \${{ secrets.SSH_PRIVATE_KEY }}
          SOURCE: "dist/"
          REMOTE_HOST: \${{ secrets.DEPLOY_HOST }}
          REMOTE_USER: \${{ secrets.DEPLOY_USER }}
          TARGET: /var/www/example.com/

GitHub Secrets 配置

GitHub 仓库 Settings → Secrets and variables → Actions 中添加:

Secret 名称 说明
SSH_PRIVATE_KEY 服务器的 SSH 私钥
DEPLOY_HOST 服务器 IP 或域名
DEPLOY_USER SSH 登录用户名

方案二:Git Hooks 自动部署

在服务器上配置 Git Hooks,本地 push 后自动拉取部署。

#!/bin/bash
# /var/repo/site.git/hooks/post-receive

#!/bin/bash
TARGET=/var/www/example.com
GIT_DIR=/var/repo/site.git

while read oldrev newrev ref
do
    if [[ $ref =~ main$ ]]; then
        echo "Deploying to production..."
        git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
        cd $TARGET
        npm ci --production
        npm run build
        sudo systemctl reload nginx
        echo "Deployment complete!"
    fi
done

服务器端配置步骤

# 1. 在服务器上创建裸仓库
sudo mkdir -p /var/repo/site.git
cd /var/repo/site.git
sudo git init --bare

# 2. 创建 post-receive hook
sudo nano hooks/post-receive
# (粘贴上面的脚本内容)
sudo chmod +x hooks/post-receive

# 3. 设置目标目录权限
sudo mkdir -p /var/www/example.com
sudo chown -R $USER:$USER /var/www/example.com

本地配置

# 添加服务器为 remote
git remote add production ssh://user@your-server/var/repo/site.git

# 推送部署
git push production main

方案三:Webhook 触发部署

#!/bin/bash
# deploy-webhook.sh - 在服务器上运行的 Webhook 监听脚本

API_PORT=9000
SECRET="your-webhook-secret"

while true; do
    request=$(nc -l -p $API_PORT)
    # 验证签名并拉取最新代码
    cd /var/www/example.com
    git pull origin main
    npm ci --production
    npm run build
    sudo systemctl reload nginx
done

安全建议

  1. 使用专门的部署用户,最小权限原则
  2. SSH 密钥添加密码短语(passphrase)
  3. 部署后清理 .env 等敏感文件
  4. 保留上一版本作为回滚备份
  5. 添加部署通知(Slack/邮件)