生產環境服務(Java、Go、Python、C++ 後端)難免因記憶體洩漏、未捕獲例外、資源耗盡而 Crash。人工重啟不可持久,需自動化守護。
/usr/local/bin/guard.sh#!/bin/bash
# 用法: guard.sh <服務名稱> <啟動命令> [檢查間隔秒數]
SERVICE_NAME="$1"
START_CMD="$2"
INTERVAL="${3:-5}"
if [[ -z "$SERVICE_NAME" || -z "$START_CMD" ]]; then
echo "Usage: $0 [interval]"
exit 1
fi
log() { echo "[$(date '+%F %T')] $*"; }
log "Starting guard for '$SERVICE_NAME' (interval: ${INTERVAL}s)"
while true; do
# 精確匹配進程(避免 grep 自身)
if ! pgrep -x "$SERVICE_NAME" >/dev/null; then
log "Process '$SERVICE_NAME' not found. Restarting..."
# 清理殘留進程
pkill -9 -x "$SERVICE_NAME" 2>/dev/null
# 在後台啟動,脫離當前 shell
eval "$START_CMD" >/dev/null 2>&1 &
sleep 2 # 給啟動緩衝
fi
sleep "$INTERVAL"
done
/usr/local/bin/start_guard.sh#!/bin/bash
# 設定 core dump 大小限制(KB),便於事後分析
ulimit -c 102400
# 啟動守護進程於背景
nohup /usr/local/bin/guard.sh myapp "/opt/myapp/bin/myapp -config /etc/myapp.conf" 10 \
>/var/log/guard-myapp.log 2>&1 &
echo $! > /var/run/guard-myapp.pid
echo "Guard started with PID $!"
# /etc/systemd/system/guard-myapp.service
[Unit]
Description=Guard for myapp
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/start_guard.sh
Restart=always
RestartSec=5
StandardOutput=append:/var/log/guard-myapp.log
StandardError=append:/var/log/guard-myapp.log
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable --now guard-myapp
無需外部腳本,直接在服務單元設定:
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
ExecStart=/opt/myapp/bin/myapp -config /etc/myapp.conf
Restart=on-failure
RestartSec=5s
StartLimitInterval=60s
StartLimitBurst=3
LimitCORE=infinity
WorkingDirectory=/opt/myapp
User=appuser
Group=appgroup
[Install]
WantedBy=multi-user.target
關鍵參數:
Restart=on-failure:非零退出碼/信號才重啟RestartSec:重啟間隔,防止快速失敗風暴StartLimitInterval/Burst:限制單位時間重啟次數,超過則放棄LimitCORE=infinity:允許生成 core dump--restart=unless-stopped# 1. 確認 core 檔案產生
ls -lh /var/lib/systemd/coredump/ # systemd-coredump 收集
# 或設定 kernel.core_pattern 指定目錄
# 2. 使用 gdb 分析
gdb /opt/myapp/bin/myapp /path/to/core.xxx
(gdb) bt full # 完整堆疊追蹤
(gdb) info locals # 區域變數
(gdb) thread apply all bt # 所有執行緒
Shell 守護腳本適合快速原型、舊系統;systemd 原生守護是單機標準化首選;容器化環境請直接使用平台級自我修復機制。核心原則:**失敗即重啟、記錄即追蹤、限流防雪崩**。