Files
syops/deploy.sh
T
2026-05-13 11:14:32 +08:00

83 lines
3.0 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
set -e
# ==============================================================================
# Hxops 部署脚本 (优化版)
# 用途: 自动拉取代码、构建前端、重启容器
# 使用: ./deploy.sh
# 备注:该文件用于手动在服务器上执行该脚本,Jenkins自动部署已不用该文件
# ==============================================================================
echo "🚀 开始部署 Hxops..."
# 1. 获取当前分支并拉取最新代码
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "📥 拉取代码 (分支: $CURRENT_BRANCH)..."
git pull origin "$CURRENT_BRANCH" || { echo "❌ git pull 失败"; exit 1; }
# 2. 检查 docker-compose 命令
if command -v docker-compose &> /dev/null; then
DC_CMD="docker-compose"
elif docker compose version &> /dev/null; then
DC_CMD="docker compose"
else
echo "❌ 未找到 docker-compose 或 docker compose 命令"
exit 1
fi
# 3. 前端构建 (在服务器上构建,确保环境一致性)
# 方案:使用 docker 临时容器构建,避免服务器安装 node
echo "🏗️ 构建前端资源..."
# 注意:这里假设 frontend/Dockerfile 已经是基于 nginx 且 COPY dist 的
# 如果我们想在服务器构建,最好修改 Dockerfile 为多阶段构建,或者使用临时容器
# 这里我们采用临时 node 容器构建 dist,然后让 docker-compose build 复制进去
# frontend 目录与当前用户信息
FRONTEND_DIR="$(pwd)/frontend"
HOST_UID="$(id -u)"
HOST_GID="$(id -g)"
# 清理旧构建产物(通过容器执行,兼容历史 root 权限文件)
echo " Cleaning old dist/node_modules..."
docker run --rm -v "${FRONTEND_DIR}:/app" -w /app node:22-alpine sh -c "rm -rf dist node_modules"
# 使用临时容器构建
echo " Running npm install & build in docker..."
docker run --rm \
-u "${HOST_UID}:${HOST_GID}" \
-e npm_config_cache=/tmp/.npm \
-v "${FRONTEND_DIR}:/app" \
-w /app \
node:22-alpine sh -c "npm install && npm run build"
if [ ! -d "frontend/dist" ]; then
echo "❌ 前端构建失败: frontend/dist 目录未生成"
exit 1
fi
# 4. 重启服务
echo "🔄 重启 Docker 服务..."
$DC_CMD down --remove-orphans || echo "⚠️ Warning: docker-compose down returned error, attempting to continue..."
$DC_CMD up -d --build
# 5. 执行数据库迁移(SQLAlchemy / Alembic)
echo "🗄️ 执行数据库表结构更新..."
$DC_CMD exec -T hxops-backend flask --app manage.py db upgrade || { echo "❌ 数据库迁移失败"; exit 1; }
# 5.1 SQLAlchemy 兜底同步(补齐缺失表,不替代 Alembic 迁移)
echo "🧩 执行 SQLAlchemy 表结构兜底同步..."
$DC_CMD exec -T hxops-backend python - <<'PY' || { echo "❌ SQLAlchemy 表结构同步失败"; exit 1; }
from app import create_app, db
app = create_app('production')
with app.app_context():
db.create_all()
print("SQLAlchemy create_all completed.")
PY
# 6. 清理未使用镜像
echo "🧹 清理旧镜像..."
docker image prune -f
echo "✅ 部署完成!"