怎么监控docker容器运行状态shell脚本

2023-05-15,

这篇文章将为大家详细讲解有关怎么监控docker容器运行状态shell脚本,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

场景

公司项目部署在docker中,由于未知原因容器偶尔会停止,需要写一个脚本监控 容器运行状态,如果容器停止了,就再启动该容器

shell脚本

#!/bin/bash
# 传入容器名称
containerName=$1
currTime=`date +"%Y-%m-%d %H:%M:%S"`
# 查看进程是否存在
exist=`docker inspect --format '{{.State.Running}}' ${containerName}`
if [ "${exist}" != "true" ]; then
 docker start ${containerName}
 # 记录
 echo "${currTime} 重启docker容器,容器名称:${containerName}" >> /mnt/xvde1/ms_ctynyd/scripts/wbwf_monitor.log
 
fi

定时任务crontab

crontab -e 进行 linux 定时任务的编辑

# 监控docker 8081 容器
*/1 * * * * sh /mnt/xvde1/ms_ctynyd/scripts/wbwf_monitor.sh server_wbwf_wbwf-app_1
# 监控 docker 7081 容器
*/1 * * * * sh /mnt/xvde1/ms_ctynyd/scripts/wbwf_monitor.sh server_hb_hb-test-app_1

补充:shell脚本判断某服务是否运行

shell脚本判断某服务是否开启

脚本如下:

#!/bin/bash
#检查服务状态,是否安装
read -p "请输入要检测的服务:" SERVICE
netstat -anp | grep $SERVICE &> /dev/null
if [ $? -eq 0 ]
then
  echo "$SERVICE服务已经启动!"
else
  rpm -q $SERVICE &> /dev/null
 
  if [ $? -eq 0 ]
  then
 echo "$SERVICE服务已安装,正在启动...."
    service $SERVICE start
  else
 echo "该服务未安装!"
 fi
fi

结果如下:

关于“怎么监控docker容器运行状态shell脚本”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

《怎么监控docker容器运行状态shell脚本.doc》

下载本文的Word格式文档,以方便收藏与打印。