docker容器运行状态监控

 此脚本用于监控容器运行状态,并将异常容器通过钉钉端报警!!!

1、编写监控脚本

[root@localhost ~]#  vim containerState-monitor.sh

!/bin/bash
##########################################################
#          监控容器运行状态,异常通过钉钉端报警脚本!!!        #
##########################################################

#取出容器的名字
containerName=`docker ps -a --format "table {{.Names}}" | grep -v "NAMES"`

#钉钉报警Token
dingtalk_openapi="https://oapi.dingtalk.com"
dingtalk_openapi_token="根据自己的token填"

#循环判断容器运行状态情况
for containerState in ${containerName[*]}
do
        #查看容器的运行状态
        exist=`docker inspect --format '{{.State.Running}}' ${containerState}`
        #判断容器运行状态,运行正常在屏幕输出即可,异常则发送报警到钉钉
        if [ "${exist}" = "true" ]; then
                echo "容器$containerState运行正常"
        else
                curl ''$dingtalk_openapi'/robot/send?access_token='$dingtalk_openapi_token'' \
                    -H 'Content-Type: application/json' \
                    -d '{"msgtype": "text",
                    "text": {
                    "content": "警告:'$containerState'服务运行异常,所在服务器为'xxx.xxx.xxx.xx'"
                    }
                    }'
        fi
done                                                                                                                 

2、测试时脚本时可能会报错如下

[root@localhost ~]# ./containerState-monitor.sh
flag provided but not defined: --format
See 'docker ps --help'.

上面的报错是因为docker版本低于1.8.0,导致-- format参数无法使用

3、将脚本中提取容器名字的命令改为如下即可

[root@localhost ~]# vim containerState-monitor.sh

containerName=`docker ps -a | awk 'NR == 1 {next} {print $NF}'`

4、如果需要指定容器监控,可以参考如下(监控所有容器不需要更改脚本!!!

[root@localhost ~]# docker ps  --format "table {{.Names}}" | grep -v "NAMES" > containerState.txt
[root@localhost ~]# vim containerState-monitor.sh

#取出容器的名字
#containerName=`docker ps -a --format "table {{.Names}}" | grep -v "NAMES"`

#将上面取出容器名字的变量更改为如下,路径根据实际情况

#通过文件所记录的容器赋值给变量
containerName=`cat /root/containerState.txt`

5、设置计划任务

[root@localhost ~]# crontab -e

*/1 * * * *   /root/containerState-monitor.sh

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT.小唐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值