×

技术教程

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

Legend Legend 发表于2023-09-02 浏览271 评论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