tomcat-inspector/image.sh#!/bin/bash
echo $(date '+%Y-%m-%d %H:%M:%S')
whoami
JAVA_HOME=/opt/java/jdk1.8.0_40
PATH=$JAVA_HOME/bin:$PATH
export PATH JAVA_HOME
port=8086
sn="tomcat-image-$port"
th="/home/dev/tomcat/$sn"
url="https://your-app-server/"
# 檢測進程數
tomcat=$(ps -ef | grep java | grep $sn | grep $port | wc -l)
if [ $tomcat -eq 0 ]; then
echo "$sn stoped."
echo "starting $sn ......"
$th/bin/startup.sh
fi
if [ $tomcat -ge 1 ]; then
tpid=$(ps -ef | grep java | grep $sn | grep $port | awk '{print $2}')
echo "$sn is running, pid=$tpid"
# HTTP 健康檢查(只取狀態碼)
httpStatus=$(curl -I -s $url -o /dev/null -w '%{http_code}')
echo "HTTP Status: $httpStatus"
if [[ -z "$httpStatus" || $httpStatus -ge 500 ]]; then
echo "killing $sn ......"
kill -9 $tpid
echo "starting $sn ......"
$th/bin/startup.sh
fi
fi
| 指令 | 用途 |
|---|---|
ps -ef | grep java | grep $sn | grep $port | 精準匹配特定 Tomcat 實例進程 |
wc -l | 統計進程數 |
awk '{print $2}' | 提取 PID |
curl -I -s -o /dev/null -w '%{http_code}' | 僅取 HTTP 狀態碼,靜默模式 |
kill -9 | 強制終止進程 |
crontab -e
# 每 5 分鐘執行一次,日誌輸出到指定檔案
*/5 * * * * /home/dev/ctl/tomcat-inspector/image.sh >> /home/dev/ctl/tomcat-inspector/logs/image.log 2>&1
systemctl 或 service 管理 Tomcat 服務(若已註冊為服務)/health)而非首頁對於關鍵業務,建議採用成熟方案:
Restart=on-failure、WatchdogSec