diff --git a/run.sh b/run.sh index b8dfe24..5945f59 100644 --- a/run.sh +++ b/run.sh @@ -10,6 +10,7 @@ set -e cd "$(dirname "$0")" +ROOT="$(pwd)" API_PORT="${PORT:-5599}" export PORT="$API_PORT" @@ -54,21 +55,21 @@ _kill_port() { } _kill_port -# 后台启动 API:优先 pm2,否则 nohup +# 后台启动 API:优先 pm2,否则 nohup(ROOT 与 PORT 已在上方定义) if [ -n "$USE_PM2" ] && command -v pm2 >/dev/null 2>&1; then echo "[run.sh] 使用 pm2 启动 API(端口 ${API_PORT})..." - (cd server && npm install --no-audit --no-fund --silent && pm2 delete view-airtep-api 2>/dev/null; true) - (cd server && pm2 start index.js --name view-airtep-api) + (cd "$ROOT/server" && npm install --no-audit --no-fund --silent && pm2 delete view-airtep-api 2>/dev/null; true) + (cd "$ROOT/server" && PORT="$API_PORT" pm2 start index.js --name view-airtep-api) pm2 save 2>/dev/null || true echo "[run.sh] API 已由 pm2 托管。查看: pm2 list / pm2 logs view-airtep-api" elif command -v nohup >/dev/null 2>&1; then echo "[run.sh] 使用 nohup 后台启动 API(端口 ${API_PORT})..." - mkdir -p logs - nohup bash start-api.sh >> logs/api.log 2>&1 & - echo "[run.sh] API 已在后台运行。查看日志: tail -f logs/api.log" + mkdir -p "$ROOT/logs" + nohup bash "$ROOT/start-api.sh" >> "$ROOT/logs/api.log" 2>&1 & + echo "[run.sh] API 已在后台运行。查看日志: tail -f $ROOT/logs/api.log" else echo "[run.sh] 前台启动 API(Ctrl+C 会停止服务)..." - exec bash start-api.sh + exec bash "$ROOT/start-api.sh" fi echo "[run.sh] 部署完成。前端静态在 dist/,API 端口 ${API_PORT}。" diff --git a/start-api.sh b/start-api.sh index f69f4fd..3a777cd 100644 --- a/start-api.sh +++ b/start-api.sh @@ -8,6 +8,22 @@ cd "$(dirname "$0")/server" PORT="${PORT:-5599}" export PORT +# 释放端口,避免 EADDRINUSE(上次未退出或多次启动) +if command -v lsof >/dev/null 2>&1; then + pids=$(lsof -t -i ":$PORT" 2>/dev/null) || true + if [ -n "$pids" ]; then + echo "[720yun-offline-api] 停止占用端口 ${PORT} 的进程: $pids" + echo "$pids" | xargs kill 2>/dev/null || true + sleep 1 + fi +elif command -v fuser >/dev/null 2>&1; then + if fuser -n tcp "$PORT" >/dev/null 2>&1; then + echo "[720yun-offline-api] 停止占用端口 ${PORT} 的进程..." + fuser -k "$PORT/tcp" 2>/dev/null || true + sleep 1 + fi +fi + echo "[720yun-offline-api] 安装依赖..." npm install --no-audit --no-fund