下面的腳本是生產可用,可靠的sh腳本,用于監控 .NET 應用程序并自動重啟。
假如你打包發布到Linux的程序名稱為MyAspDemo;
推薦打包模式為框架依賴:需要在Linux上安裝對應的donet版本;
1.在Linux下新建一個文件,如:
mkdir dotnet-monitor.sh
如上新建了一個名為 dotnet-monitor.sh的腳本文件,打開腳本文件,添加如下內容:
#!/bin/bash# 配置
APP_NAME="MyAspDemo" # 應用名稱
APP_DIR="/opt/services/publish" # 應用所在目錄
APP_DLL="MyAspDemo.Api.dll" # 主程序集
DOTNET_CMD="dotnet" # dotnet 命令
LOG_FILE="/var/log/dotnet-monitor.log" # 日志文件
CHECK_INTERVAL=30 # 檢查間隔(秒)
MAX_RESTARTS=5 # 最大重啟次數(防崩潰循環)
RESTART_COOLDOWN=60 # 重啟冷卻時間(秒)# 函數:記錄日志
log() {echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}# 函數:檢查應用是否在運行
is_running() {pgrep -f "dotnet.*$APP_DLL" > /dev/null
}# 函數:啟動應用
start_app() {log "啟動應用: $APP_NAME"cd "$APP_DIR" || { log "無法進入目錄: $APP_DIR"; return 1; }nohup $DOTNET_CMD "$APP_DLL" > /dev/null 2>&1 &sleep 5 # 等待進程啟動if is_running; thenlog "應用已啟動"return 0elselog "啟動失敗"return 1fi
}# 函數:停止應用
stop_app() {log "停止應用: $APP_NAME"pkill -f "dotnet.*$APP_DLL"sleep 3
}# 主循環
restart_count=0
last_restart=$(date +%s)log "啟動,監控: $APP_NAME"while true; doif ! is_running; thenlog "應用未運行,嘗試重啟..."# 檢查是否在冷卻期內(防頻繁重啟)current_time=$(date +%s)time_since_last=$((current_time - last_restart))if [ $restart_count -ge $MAX_RESTARTS ] && [ $time_since_last -lt $RESTART_COOLDOWN ]; thenlog "重啟次數過多,進入冷卻期..."sleep $RESTART_COOLDOWNrestart_count=0last_restart=$(date +%s)elsestop_appif start_app; thenrestart_count=$((restart_count + 1))last_restart=$(date +%s)elselog "啟動失敗,等待下次檢查..."fifielselog "應用正在運行"fisleep $CHECK_INTERVAL
done
2.為剛剛創建的腳本文件添加執行權限:
sudo chmod +x /opt/dotnet-monitor.sh
3.創建systemd service文件,如下:
vi /etc/systemd/system/dotnet-monitor.service
添加如下內容:
[Unit]
Description=DotNet Monitor
After=network.target[Service]
Type=simple
User=www-admin //自定義名稱
WorkingDirectory=/opt
ExecStart=/opt/service/dotnet-monitor.sh //腳本所在目錄
Restart=always
RestartSec=10[Install]
WantedBy=multi-user.target
4.啟動服務:
sudo systemctl daemon-reexec
sudo systemctl enable dotnet-monitor.service
sudo systemctl start dotnet-monitor.service
ok