deploy.sh 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/bin/bash
  2. # 设置错误时退出
  3. set -e
  4. # 配置变量
  5. PROJECT_NAME="tweb-api"
  6. PROJECT_DIR="/var/www/$PROJECT_NAME"
  7. username="wuyi"
  8. password="hXE8ZjQ^Q46V7n"
  9. GIT_REPO="https://git.izouma.com/wuyi/tweb-api.git"
  10. GIT_REPO_WITH_AUTH="https://${username}:${password}@git.izouma.com/wuyi/tweb-api.git"
  11. echo "🚀 开始部署 $PROJECT_NAME..."
  12. # 检查并安装 yarn
  13. check_and_install_yarn() {
  14. if ! command -v yarn &> /dev/null; then
  15. echo "📦 安装 yarn..."
  16. if command -v npm &> /dev/null; then
  17. npm install -g yarn
  18. else
  19. echo "❌ 请先安装 Node.js 和 npm"
  20. exit 1
  21. fi
  22. fi
  23. }
  24. check_and_install_yarn
  25. # 检查项目目录是否存在
  26. if [ ! -d "$PROJECT_DIR" ]; then
  27. echo "📥 克隆项目..."
  28. if git clone -b main "$GIT_REPO_WITH_AUTH" "$PROJECT_DIR"; then
  29. echo "✅ 项目克隆成功"
  30. else
  31. echo "❌ 项目克隆失败"
  32. exit 1
  33. fi
  34. fi
  35. # 进入项目目录
  36. cd "$PROJECT_DIR"
  37. # 检查是否是 Git 仓库
  38. if [ ! -d ".git" ]; then
  39. echo "❌ 项目目录不是 Git 仓库"
  40. exit 1
  41. fi
  42. # 检查 package.json 是否存在
  43. if [ ! -f "package.json" ]; then
  44. echo "❌ package.json 文件不存在"
  45. exit 1
  46. fi
  47. # Git 操作函数
  48. handle_git_operations() {
  49. git remote set-url origin "$GIT_REPO_WITH_AUTH"
  50. if git pull origin main; then
  51. echo "✅ 代码更新成功"
  52. else
  53. echo "❌ Git 拉取失败"
  54. echo "是否继续部署(跳过代码拉取)?(y/N)"
  55. read -r response
  56. if [[ ! "$response" =~ ^[Yy]$ ]]; then
  57. echo "部署已取消"
  58. exit 1
  59. fi
  60. fi
  61. }
  62. handle_git_operations
  63. # 停止现有的 PM2 进程
  64. pm2 delete tweb-api 2>/dev/null || true
  65. # 安装依赖
  66. yarn install
  67. # 清理旧的构建文件
  68. rm -rf dist
  69. # 构建项目
  70. yarn build
  71. # 检查构建是否成功
  72. if [ ! -f "dist/app.js" ]; then
  73. echo "❌ 构建失败: dist/app.js 文件不存在"
  74. exit 1
  75. fi
  76. # 替换配置文件
  77. cp .env.production dist/.env
  78. cp package.json dist/package.json
  79. # 检查 PM2 应用是否已存在并启动
  80. if pm2 list | grep -q "tweb-api"; then
  81. echo "🔄 重启现有的 PM2 应用..."
  82. pm2 restart tweb-api --node-args="--experimental-specifier-resolution=node"
  83. else
  84. echo "🚀 启动新的 PM2 应用..."
  85. pm2 start dist/app.js --name tweb-api --node-args="--experimental-specifier-resolution=node"
  86. fi
  87. pm2 save
  88. echo "✅ 部署完成!"
  89. pm2 status
  90. echo "📋 显示日志(按 Ctrl+C 退出):"
  91. pm2 logs tweb-api