本文目录导读:

我来详细介绍Shell脚本配置容器监控面板的方法:
基础监控脚本
CPU和内存监控
#!/bin/bash
# 容器资源监控脚本
CONTAINERS=$(docker ps --format "{{.Names}}")
echo "容器资源使用情况:"
echo "------------------------"
for container in $CONTAINERS; do
echo "容器: $container"
# CPU使用率
cpu_usage=$(docker stats $container --no-stream --format "{{.CPUPerc}}")
echo " CPU: $cpu_usage"
# 内存使用
mem_usage=$(docker stats $container --no-stream --format "{{.MemUsage}}")
echo " 内存: $mem_usage"
# 网络流量
network=$(docker stats $container --no-stream --format "{{.NetIO}}")
echo " 网络: $network"
# 磁盘IO
block_io=$(docker stats $container --no-stream --format "{{.BlockIO}}")
echo " 磁盘: $block_io"
echo ""
done
实时监控面板
#!/bin/bash
# 实时容器监控面板
show_container_panel() {
clear
echo "╔══════════════════════════════════════╗"
echo "║ Docker容器监控面板 ║"
echo "╠══════════════════════════════════════╣"
# 获取运行中的容器列表
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | head -1
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | tail -n +2
echo "╠══════════════════════════════════════╣"
# 显示资源使用
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"
echo "╚══════════════════════════════════════╝"
}
# 持续监控
while true; do
show_container_panel
echo "按 Ctrl+C 退出监控"
sleep 5
done
高级监控配置
#!/bin/bash
# 配置监控参数
MONITOR_INTERVAL=10
ALERT_CPU_THRESHOLD=80
ALERT_MEM_THRESHOLD=90
LOG_FILE="/var/log/container_monitor.log"
WEBHOOK_URL="https://your-webhook/alert"
# 初始化监控
init_monitoring() {
mkdir -p /var/log/container_monitor
touch $LOG_FILE
}
# 监控单个容器
monitor_container() {
local container=$1
# 获取容器状态
local status=$(docker inspect --format='{{.State.Status}}' $container 2>/dev/null)
if [ "$status" != "running" ]; then
log_event "WARNING" "容器 $container 状态异常: $status"
return
fi
# 获取资源使用
local cpu=$(docker stats $container --no-stream --format "{{.CPUPerc}}" | sed 's/%//')
local mem_percent=$(docker stats $container --no-stream --format "{{.MemPerc}}" | sed 's/%//')
# 检查阈值
if (( $(echo "$cpu > $ALERT_CPU_THRESHOLD" | bc -l) )); then
send_alert "CPU告警: $container CPU使用率: $cpu%"
fi
if (( $(echo "$mem_percent > $ALERT_MEM_THRESHOLD" | bc -l) )); then
send_alert "内存告警: $container 内存使用率: $mem_percent%"
fi
# 记录日志
log_event "INFO" "$container CPU: ${cpu}% 内存: ${mem_percent}%"
}
# 日志记录
log_event() {
local level=$1
local message=$2
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" >> $LOG_FILE
}
# 发送告警
send_alert() {
local message=$1
# Webhook通知
if [ -n "$WEBHOOK_URL" ]; then
curl -X POST -H "Content-Type: application/json" \
-d "{\"text\":\"$message\"}" \
$WEBHOOK_URL 2>/dev/null
fi
# 本地通知
echo "ALERT: $message" | wall 2>/dev/null
}
# 主循环
main_loop() {
init_monitoring
while true; do
local containers=$(docker ps -q)
for container in $containers; do
monitor_container $container &
done
wait
sleep $MONITOR_INTERVAL
done
}
# 执行监控
main_loop
带Web前端的监控面板
#!/bin/bash
# 生成HTML监控面板
generate_html() {
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
local container_count=$(docker ps -q | wc -l)
cat > /tmp/dashboard.html <<EOF
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="5">Container Monitor</title>
<style>
body { font-family: Arial, sans-serif; background: #1a1a2e; color: #fff; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.header { text-align: center; margin-bottom: 30px; }
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
.card { background: #16213e; padding: 20px; border-radius: 10px; }
.running { color: #4ecca3; }
.stopped { color: #ff6b6b; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px; text-align: left; border-bottom: 1px solid #333; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>容器监控面板</h1>
<p>更新时间: $timestamp</p>
<p>运行容器数: $container_count</p>
</div>
<div class="stats" id="containerStats">
EOF
# 为每个容器生成状态卡片
docker ps --format "{{.Names}} {{.Status}} {{.Ports}}" | while read line; do
name=$(echo $line | awk '{print $1}')
status=$(echo $line | awk '{print $2}')
ports=$(echo $line | awk '{print $3}')
cat >> /tmp/dashboard.html <<EOF
<div class="card">
<h3>$name</h3>
<p>状态: <span class="$( [ "$status" = "Up" ] && echo "running" || echo "stopped" )">$status</span></p>
<p>端口: $ports</p>
<p>CPU: $(docker stats $name --no-stream --format "{{.CPUPerc}}")</p>
<p>内存: $(docker stats $name --no-stream --format "{{.MemPerc}}")</p>
</div>
EOF
done
cat >> /tmp/dashboard.html <<EOF
</div>
</div>
</body>
</html>
EOF
}
# 启动Web服务器
start_web_server() {
# 使用Python内置HTTP服务器
cd /tmp
python3 -m http.server 8080 &
echo "监控面板: http://localhost:8080/dashboard.html"
}
# 执行
generate_html
start_web_server
# 持续更新
while true; do
sleep 5
generate_html
done
完整监控配置脚本
#!/bin/bash
# 容器监控面板完整配置脚本
# 配置参数
CONFIG_DIR="$HOME/.container_monitor"
ALERT_EMAIL="admin@example.com"
SLACK_WEBHOOK="https://hooks.slack.com/services/xxx"
# 初始化配置
init_config() {
mkdir -p $CONFIG_DIR/{logs,configs}
# 创建默认配置文件
cat > $CONFIG_DIR/configs/monitor.conf <<EOF
# 监控配置
MONITOR_INTERVAL=30
CPU_THRESHOLD=80
MEM_THRESHOLD=85
DISK_THRESHOLD=90
RESTART_FAILED_CONTAINERS=true
LOG_RETENTION_DAYS=7
EOF
echo "配置文件已创建: $CONFIG_DIR/configs/monitor.conf"
}
# 加载配置
load_config() {
if [ -f "$CONFIG_DIR/configs/monitor.conf" ]; then
source "$CONFIG_DIR/configs/monitor.conf"
fi
}
# 显示监控面板
show_dashboard() {
clear
echo "======================================"
echo " Docker容器监控面板"
echo "======================================"
echo ""
# 系统概览
echo "系统信息:"
echo " 主机名: $(hostname)"
echo " 时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo " 运行时间: $(uptime -p)"
echo ""
# Docker信息
echo "Docker信息:"
echo " 总容器数: $(docker ps -aq | wc -l)"
echo " 运行中: $(docker ps -q | wc -l)"
echo " 停止: $(docker ps -aq | wc -l) - $(docker ps -q | wc -l) | bc)"
echo ""
# 详细容器状态
echo "容器详情:"
printf "%-20s %-10s %-10s %-10s %-10s\n" "名称" "状态" "CPU%" "内存%" "重启次数"
printf "%-20s %-10s %-10s %-10s %-10s\n" "--------------------" "----------" "----------" "----------" "----------"
for container in $(docker ps -aq); do
name=$(docker inspect --format='{{.Name}}' $container | sed 's/^\/\(.*\)/\1/')
status=$(docker inspect --format='{{.State.Status}}' $container)
cpu=$(docker stats $container --no-stream --format "{{.CPUPerc}}" 2>/dev/null || echo "N/A")
mem=$(docker stats $container --no-stream --format "{{.MemPerc}}" 2>/dev/null || echo "N/A")
restart=$(docker inspect --format='{{.RestartCount}}' $container)
printf "%-20s %-10s %-10s %-10s %-10s\n" "$name" "$status" "$cpu" "$mem" "$restart"
done
}
# 自动修复功能
auto_heal() {
load_config
if [ "$RESTART_FAILED_CONTAINERS" = "true" ]; then
for container in $(docker ps -aq --filter status=exited --filter status=dead); do
echo "尝试重启容器: $container"
docker restart $container
log_event "INFO" "自动重启容器: $container"
done
fi
}
# 日志清理
cleanup_logs() {
load_config
find $CONFIG_DIR/logs -name "*.log" -mtime +$LOG_RETENTION_DAYS -delete
echo "日志清理完成"
}
# 主函数
main() {
case "$1" in
start)
init_config
echo "启动监控面板..."
while true; do
show_dashboard
auto_heal
sleep $MONITOR_INTERVAL
done
;;
stop)
echo "停止监控面板"
pkill -f "container_monitor.sh"
;;
status)
show_dashboard
;;
config)
echo "当前配置:"
cat $CONFIG_DIR/configs/monitor.conf
;;
clean)
cleanup_logs
;;
*)
echo "用法: $0 {start|stop|status|config|clean}"
;;
esac
}
# 执行
main "$@"
使用说明
安装和运行
# 赋予执行权限 chmod +x container_monitor.sh # 启动监控 ./container_monitor.sh start # 查看状态 ./container_monitor.sh status # 修改配置 ./container_monitor.sh config
配置告警
# 配置告警阈值
cat > /etc/docker/daemon.json <<EOF
{
"live-restore": true,
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}
EOF
# 重启Docker服务
systemctl restart docker
这个监控面板提供了完整的容器监控解决方案,包括实时监控、告警通知、自动恢复等功能。