flnxi-Wu/scripts/deploy/deploy-remote-template.sh
WuYongJie f646b71813
Some checks failed
CI Check / check (push) Has been cancelled
chore: 初始化本地仓库并同步最近改动
2025-11-18 17:50:16 +08:00

102 lines
2.6 KiB
Bash
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
cd PROJECT_PATH_PLACEHOLDER
echo "========================================"
echo "开始部署..."
echo "========================================"
# 备份重要数据
echo "[1/6] 备份数据..."
if [ -d "uploads" ]; then
mkdir -p backups
backup_dir="backups/uploads-$(date +%Y%m%d-%H%M%S)"
cp -r uploads "$backup_dir" 2>/dev/null || true
echo " ✓ 上传目录已备份到 $backup_dir"
fi
# 检查 Docker 和 Docker Compose
echo "[2/6] 检查环境..."
if ! command -v docker > /dev/null 2>&1; then
echo "错误: Docker 未安装" >&2
exit 1
fi
# 使用 docker compose 或 docker-compose
if docker compose version > /dev/null 2>&1; then
DOCKER_COMPOSE="docker compose"
elif docker-compose version > /dev/null 2>&1; then
DOCKER_COMPOSE="docker-compose"
else
echo "错误: Docker Compose 未安装" >&2
exit 1
fi
echo " ✓ 使用: $DOCKER_COMPOSE"
# 停止旧容器(优雅停止)
echo "[3/6] 停止旧容器..."
$DOCKER_COMPOSE down --timeout 30 2>/dev/null || true
echo " ✓ 旧容器已停止"
# 构建新镜像(使用缓存,除非指定 --no-cache)
echo "[4/6] 构建 Docker 镜像..."
BUILD_FLAG_PLACEHOLDER
if [ -n "$BUILD_FLAG" ]; then
echo " ⚠ 使用 --no-cache 模式(构建时间较长)"
$DOCKER_COMPOSE build $BUILD_FLAG app && $DOCKER_COMPOSE up -d app
else
echo " ✓ 使用智能构建缓存(推荐)"
$DOCKER_COMPOSE up -d --build app
fi
if [ $? -ne 0 ]; then
echo "错误: 容器构建或启动失败" >&2
exit 1
fi
echo " ✓ 容器构建并启动完成"
# 等待容器就绪
echo " ⏳ 等待容器就绪..."
sleep 10
# 检查容器状态
max_attempts=30
attempt=0
while [ $attempt -lt $max_attempts ]; do
if $DOCKER_COMPOSE ps app | grep -q "Up"; then
echo " ✓ 容器运行中"
break
fi
attempt=$((attempt + 1))
sleep 2
done
if [ $attempt -eq $max_attempts ]; then
echo " ⚠ 警告: 容器可能未正常启动,请检查日志"
fi
# 执行数据库迁移(如果需要)
echo "[6/6] 检查数据库迁移..."
if [ -f prisma/schema.prisma ]; then
$DOCKER_COMPOSE exec -T app npx prisma db push --accept-data-loss --schema=/app/prisma/schema.prisma 2>/dev/null || echo " ⚠ 数据库迁移跳过或已完成"
fi
# 显示部署结果
echo ""
echo "========================================"
echo "部署完成!"
echo "========================================"
echo ""
echo "容器状态:"
$DOCKER_COMPOSE ps
echo ""
echo "应用日志(最后 30 行):"
$DOCKER_COMPOSE logs app --tail=30
echo ""
echo "如需查看完整日志,请运行:"
echo " $DOCKER_COMPOSE logs -f app"
echo ""