温馨提示×

ubuntu中thinkphp项目如何实现自动化部署

小樊
36
2026-01-01 07:16:06
栏目: 编程语言

Ubuntu下 ThinkPHP 项目自动化部署实战

一、方案总览

  • 准备运行环境:安装 PHP 7.4+Nginx/ApacheComposerMySQL,将站点根目录指向 public,并配置 URL 重写。
  • 代码交付方式:使用 Git 管理代码;服务器通过 SSH 免密拉取,或托管平台通过 Webhook 触发部署脚本。
  • 自动化流程:在服务器编写部署脚本,完成拉取代码、安装依赖、发布资源、设置权限、清缓存、重启服务等步骤,实现一键或自动触发部署。

二、环境与目录准备

  • 安装基础组件(以 Ubuntu 20.04/22.04 为例):
    • sudo apt update && sudo apt install -y php php-fpm php-mysql php-mbstring php-xml php-curl nginx mysql-server composer
  • 目录与权限:
    • 代码目录:/var/www/your_project;Web 根目录:/var/www/your_project/public
    • 建议所有者为 www-data,便于 PHP-FPM 写入:sudo chown -R www-data:www-data /var/www/your_project
    • 运行目录可写:chmod -R 755 runtime(必要时 775,视 umask 而定)
  • Nginx 站点配置要点(/etc/nginx/sites-available/your_project):
    • root 指向 public;index 包含 index.php
    • 隐藏入口:try_files $uri $uri/ /index.php?$query_string;
    • PHP 处理:fastcgi_pass 指向 /run/php/php7.4-fpm.sock(按实际 PHP 版本调整)
  • 生产与安全:
    • 关闭调试:config/app.php 中 ‘app_debug’ => false
    • 建议启用 HTTPS(如 Let’s Encrypt)

三、自动化部署脚本

  • 目标:拉取最新代码 → 安装依赖 → 发布资源 → 设置权限 → 清缓存 → 重启服务
  • 示例脚本 deploy.sh(可按需扩展数据库迁移、队列等)
#!/usr/bin/env bash
set -e

APP_DIR="/var/www/your_project"
REPO_URL="git@github.com:username/your_project.git"
BRANCH="${1:-main}"
LOG_FILE="/var/log/deploy.log"

log() {
  echo "[$(date '+%F %T')] $*" | tee -a "$LOG_FILE"
}

# 1) 拉取代码(裸仓库或工作区均可,这里演示工作区)
if [ ! -d "$APP_DIR/.git" ]; then
  log "首次克隆 $REPO_URL$APP_DIR"
  git clone -b "$BRANCH" "$REPO_URL" "$APP_DIR"
else
  log "更新 $APP_DIR 分支 $BRANCH"
  git -C "$APP_DIR" fetch --all
  git -C "$APP_DIR" reset --hard "origin/$BRANCH"
  git -C "$APP_DIR" clean -fd
fi

# 2) 安装依赖
log "安装 Composer 依赖"
composer install --optimize-autoloader --no-dev -o -d "$APP_DIR"

# 3) 发布资源(ThinkPHP 6 常用)
if [ -f "$APP_DIR/artisan" ]; then
  log "发布 ThinkPHP 资源"
  php "$APP_DIR/artisan" config:cache
  php "$APP_DIR/artisan" route:cache
  php "$APP_DIR/artisan" view:cache
fi

# 4) 权限
log "设置目录权限"
chown -R www-data:www-data "$APP_DIR"
find "$APP_DIR" -type d -exec chmod 755 {} \;
find "$APP_DIR" -type f -exec chmod 644 {} \;
chmod -R 755 "$APP_DIR/runtime"

# 5) 重启服务
log "重启 PHP-FPM 与 Nginx"
systemctl reload php7.4-fpm || systemctl restart php7.4-fpm
systemctl reload nginx || systemctl restart nginx

log "部署完成 -> $APP_DIR (branch: $BRANCH)"
  • 使用方式:
    • 赋权:chmod +x deploy.sh
    • 手动部署:./deploy.sh main
    • 日志:tail -f /var/log/deploy.log

四、触发方式与免密拉取

  • SSH 免密拉取(推荐)
    • 生成密钥:ssh-keygen -t ed25519 -C “deploy@server”
    • 将公钥(~/.ssh/id_ed25519.pub)添加到 GitHub/GitLab 的 Deploy Keys(只读即可)
    • 测试:ssh -T git@github.com
  • Git Hooks(服务器侧自动部署)
    • 裸仓库方式:/var/repo/your_project.git/hooks/post-receive
    • 示例脚本(检出到站点目录):
      #!/usr/bin/env bash
      TARGET="/var/www/your_project"
      GIT_DIR="/var/repo/your_project.git"
      BRANCH="main"
      while read oldrev newrev ref; do
        if [[ $ref = refs/heads/$BRANCH ]]; then
          git --work-tree="$TARGET" --git-dir="$GIT_DIR" checkout -f "$BRANCH"
          bash "$TARGET/deploy.sh" "$BRANCH"
        fi
      done
      
    • 赋权:chmod +x post-receive
  • Webhooks(托管平台触发)
    • 在服务器放置接收脚本(如 /var/www/hook.php),校验签名后执行部署脚本
    • 示例要点(简化版):
      <?php
      $secret = 'your_webhook_secret';
      $body = file_get_contents('php://input');
      $sig   = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';
      if (!hash_equals('sha256=' . hash_hmac('sha256', $body, $secret), $sig)) {
        http_response_code(403); exit('签名验证失败');
      }
      $payload = json_decode($body, true);
      if (($payload['ref'] ?? '') === 'refs/heads/main') {
        exec('cd /var/www/your_project && bash deploy.sh main >> /var/log/deploy.log 2>&1 &');
        echo '部署已触发';
      }
      
    • 在 GitHub/GitLab 项目设置中添加 Webhook URL:https://yourdomain.com/hook.php(建议仅推送事件、启用 SSL)

五、常见问题与加固建议

  • 入口与重写:确保 Nginx root 指向 public,并使用 try_files 或 rewrite 将所有请求转发到 index.php;隐藏 index.php 入口。
  • 权限与安全:
    • 运行用户与组统一为 www-data;runtime、storage 等目录可写
    • .env 与敏感配置仅本机可读:chmod 600 .env
    • Webhook 务必校验 签名来源 IP,避免未授权触发
  • 缓存与优化:生产环境执行 配置/路由/视图缓存,减少文件 I/O
  • 日志与回滚:部署日志写入文件;保留最近几次发布包或 Git 标签,便于快速回滚
  • 服务重启:代码或依赖变更后,按需 reload/restart PHP-FPM 与 Nginx,避免长连接异常

0