Files
peipei-backend/deploy-docker.sh
2025-11-04 22:00:31 -05:00

75 lines
2.1 KiB
Bash
Executable File

#!/usr/bin/env bash
# Docker deployment script with safety checks
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
prompt_yes_no() {
local prompt="$1"
local default_no_text="${2:-[y/N]}"
local answer
read -r -p "$prompt $default_no_text " answer || true
answer="${answer:-}"; answer="${answer,,}"
[[ "$answer" == "y" || "$answer" == "yes" ]]
}
echo "=== 部署前检查开始 ==="
if ! git -C "$SCRIPT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "错误: 当前目录不在 Git 仓库内,无法继续。"
exit 1
fi
CURRENT_BRANCH=$(git -C "$SCRIPT_DIR" rev-parse --abbrev-ref HEAD)
if [[ "$CURRENT_BRANCH" != "master" ]]; then
echo "错误: 当前分支为 '$CURRENT_BRANCH'。仅允许在 master 分支上部署。"
exit 1
fi
if ! prompt_yes_no "你跑测试了吗?要不要我帮你跑?"; then
echo "跳过测试执行。"
else
echo "开始执行测试: mvn test"
if ! mvn test; then
echo "测试未通过,部署流程终止。"
exit 1
fi
echo "测试通过。"
fi
if ! prompt_yes_no "你备份数据库了吗?确认已备份请输入 y"; then
echo "请先完成数据库备份,再运行部署脚本。"
exit 1
fi
if ! prompt_yes_no "你 commit 了吗?确认已提交请输入 y"; then
echo "请在提交后再运行部署脚本。"
exit 1
fi
if ! git -C "$SCRIPT_DIR" diff --quiet; then
echo "错误: 检测到未暂存的本地修改,请处理后再试。"
exit 1
fi
if ! git -C "$SCRIPT_DIR" diff --cached --quiet; then
echo "错误: 检测到未提交的暂存修改,请提交后再试。"
exit 1
fi
echo "部署前检查通过。"
# Get current time and format it
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "Deployment started at: $current_time"
echo "Connecting to server to update docker container..."
# SSH into the server, pull the latest image and restart the container
ssh root@122.51.20.105 "source /etc/profile; cd ~; docker compose pull && docker compose up -d"
echo "Docker container updated!"
# Get current time and format it
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "Deployment finished at: $current_time"