feat: 添加服务器重启脚本

添加restart.sh脚本用于管理服务器进程,包含以下功能:
- 自动查找并停止现有服务器进程
- 启动新的服务器实例
- 管理进程ID文件和日志输出
- 支持端口配置和状态检查
```
This commit is contained in:
2026-03-19 15:37:29 +08:00
parent f8dfad26a4
commit f8374f5e0d

83
restart.sh Normal file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="$SCRIPT_DIR/logs"
PID_FILE="$LOG_DIR/server.pid"
LOG_FILE="$LOG_DIR/server.log"
mkdir -p "$LOG_DIR"
PORT="${PORT:-}"
if [[ -z "$PORT" && -f "$SCRIPT_DIR/.env" ]]; then
PORT="$(grep -E '^PORT=' "$SCRIPT_DIR/.env" | tail -n 1 | cut -d '=' -f 2- | tr -d '\r' || true)"
fi
PORT="${PORT:-5000}"
find_project_server_pids() {
pgrep -f "node src/server.js" | while read -r pid; do
[[ -n "$pid" ]] || continue
[[ -d "/proc/$pid" ]] || continue
local cwd
cwd="$(readlink -f "/proc/$pid/cwd" 2>/dev/null || true)"
if [[ "$cwd" == "$SCRIPT_DIR" ]]; then
echo "$pid"
fi
done
}
stop_existing_server() {
local pids
pids="$(find_project_server_pids || true)"
if [[ -z "$pids" ]]; then
echo "No existing server process found for $SCRIPT_DIR"
return
fi
echo "Stopping existing server process(es): $pids"
while read -r pid; do
[[ -n "$pid" ]] || continue
kill "$pid" 2>/dev/null || true
done <<< "$pids"
sleep 2
local remaining
remaining="$(find_project_server_pids || true)"
if [[ -n "$remaining" ]]; then
echo "Force killing remaining process(es): $remaining"
while read -r pid; do
[[ -n "$pid" ]] || continue
kill -9 "$pid" 2>/dev/null || true
done <<< "$remaining"
fi
}
start_server() {
cd "$SCRIPT_DIR"
echo "Starting server from $SCRIPT_DIR on port $PORT"
nohup node src/server.js >> "$LOG_FILE" 2>&1 &
local pid=$!
echo "$pid" > "$PID_FILE"
echo "Started PID: $pid"
}
show_status() {
sleep 2
echo
echo "Active project server process(es):"
find_project_server_pids || true
echo
echo "Port check:"
ss -lntp 2>/dev/null | grep ":$PORT" || true
echo
echo "Recent log output:"
tail -n 30 "$LOG_FILE" 2>/dev/null || true
}
stop_existing_server
start_server
show_status