×

docker容器自动检查,不正常则重启容器

Legend Legend 发表于2023-09-02 16:09:25 浏览273 评论0

抢沙发发表评论

#!/bin/bash


current_date=$(date '+%Y-%m-%d %H:%M:%S')

docker_status=$(systemctl is-active docker)

if [ "$docker_status" != "active" ]; then
  echo "$current_date Docker server ERR"

  systemctl restart docker
  
  docker_status=$(systemctl is-active docker)

  if [ "$docker_status" = "active" ]; then
    echo "$current_date Docker ok"
  else
    echo "$current_date Docker NOT"
  fi
fi

containers=$(docker ps -aq)
for container_id in $containers; do
  container_name=$(docker inspect -f '{{.Name}}' "$container_id")
  container_name=${container_name//\//}  # 移除名称前的"/"字符

  container_status=$(docker inspect -f '{{.State.Status}}' "$container_id")

  if [ "$container_status" != "running" ]; then
    echo "$current_date Container $container_name ($container_id) ERR...restart"
    docker restart "$container_id"
  fi
done


然后加入系统定时

文件在 /var/spool/cron/crontabs

最后一行添加

* * * * * /root/docker.sh >> /var/log/docker_cron.log 2>&1

其中后面的日志文件可以去除

 >> /var/log/docker_cron.log 2>&1