当前位置: 首页 > news >正文

docker 容器健康检测与重启

docker 容器健康检测与重启

health-check.py

import docker
import time
import logging# ============================
# Logger 配置
# ============================
logger = logging.getLogger("autoheal")
logger.setLevel(logging.INFO)fmt = logging.Formatter("%(asctime)s [%(levelname)s] [autoheal] %(message)s")
ch = logging.StreamHandler()
ch.setFormatter(fmt)
logger.addHandler(ch)# ============================
# Docker 客户端
# ============================
client = docker.DockerClient(base_url='unix://var/run/docker.sock')CHECK_INTERVAL = 60
RETRY_TIMES = 3def get_health(container):try:container.reload()    # 刷新状态state = container.attrs["State"]# 容器已经停止,无需检测健康,直接返回 stoppedif state.get("Status") in ["exited", "dead", "created"]:return "stopped"if "Health" in state:return state["Health"]["Status"]   # healthy / unhealthy / startingelse:return "no-healthcheck"except Exception as e:return f"error: {e}"def check_and_restart():containers = client.containers.list(all=True)for container in containers:name = container.namestatus = get_health(container)# ------- 输出状态 -------logger.info(f"[{name}] Current health/state: {status}")# ------- 停止的容器不处理 -------if status == "stopped":logger.info(f"[{name}] Container stopped (Exited). Skip.")continue# ------- 无健康检查,跳过 -------if status == "no-healthcheck":logger.info(f"[{name}] No HEALTHCHECK. Skip.")continue# ------- 健康,不处理 -------if status == "healthy":continue# ------- 不健康,进行三次重试 -------if status == "unhealthy":logger.warning(f"[{name}] Unhealthy! Starting retry checks...")for retry in range(1, RETRY_TIMES + 1):time.sleep(CHECK_INTERVAL)status = get_health(container)logger.info(f"[{name}] Retry {retry}/{RETRY_TIMES}: {status}")# 可能已经被 stop 掉if status == "stopped":logger.info(f"[{name}] Container is stopped during retry. Skip restart.")breakif status == "healthy":logger.info(f"[{name}] Back to healthy. No restart needed.")breakelse:# 3 次全部 unhealthy,执行重启logger.warning(f"[{name}] Still unhealthy after {RETRY_TIMES} retries. Restarting...")container.restart()logger.info(f"[{name}] Restart issued.")if __name__ == "__main__":logger.info("=== Autoheal service started ===")while True:check_and_restart()time.sleep(10)   # 主循环每 10s 执行一次

Dockerfile

FROM python:3.10-slimRUN pip install dockerCOPY check_health.py /check_health.pyCMD ["python", "/check_health.py"]

构建镜像

docker build -t health-check:v1.0 .

启动检测容器

docker run -d \-v /var/run/docker.sock:/var/run/docker.sock \-v /etc/localtime:/etc/localtime \--name health-checker \health-check:v1.0
http://www.jsqmd.com/news/68170/

相关文章:

  • 2025年12月标书制作服务标杆企业推荐:拆除工程标书、市政工程标书、道路工程标书、重庆睿标通招投标咨询有限公司
  • 2025上海留学中介机构汇总
  • PMP培训十大最佳机构挑选指南白皮书
  • 2025年12月恒温恒湿机最新推荐厂家:机房、档案室、展柜专用设备选型指南​
  • 2025上海留学中介机构哪家好点
  • 2025上海留学中介哪家比较好一点
  • 2025年EPE珍珠棉板材厂家权威推荐榜单:EPE珍珠棉卷材‌/EPE珍珠棉异型材‌/珍珠棉异型材‌‌源头厂家精选
  • 真机燃烧极限挑战,阳光电源何以定义储能安全新标杆?
  • 2025 年 12 月悬臂吊/塔吊厂家与租赁服务权威推荐榜:立柱式、移动式、大型屋面吊,实力工厂与可靠服务商全景解析
  • 2025年12月自动车辆计数与体积测量系统标杆厂家最新推荐:激光雷达精准赋能,引领矿山、土石方管理新标准
  • 2025上海留学中介最好的是哪家官网的
  • 2025年别墅轨道式老人座椅电梯厂家推荐:靠谱专为老人设计上
  • 2025上海知名留学机构有哪些
  • @ConditionalOnProperty
  • 2025年日东胶带推荐厂商TOP5:日东胶带专业制造商有哪些
  • 12 月年度收官!2025GEO 公司综合实力 TOP 榜单新鲜出炉
  • 2025年度广东污水处理集装箱生产企业推荐:稳定性与专业度双
  • 2025AI搜索日化获客AI搜索稳定获客AI搜索社交获客TO
  • 2025年中国竹制品制造厂排名:竹制品厂家哪家好?
  • 2025年靠谱适老化座椅电梯公司推荐:专为老人设计上下楼座椅
  • 2025年五大防伪企业排名,有实力的防伪公司推荐,大型防伪企
  • 2025上海评价高/售后完善/靠谱装修装饰设计公司TOP5:
  • 2025上海评价高/售后完善/靠谱装修装饰设计公司TOP5:
  • 2025年五大晶体炉设备制造商推荐:晶体炉装置制造厂哪家售后
  • 2025年实力强的隐形车衣公司推荐,服务不错的隐形车衣专业公
  • 北京电动轮椅2025年12月全维度测评:续航/安全/性价比TOP10权威榜单
  • 2025家用楼梯升降椅品牌TOP5权威推荐:爬楼梯专用施工与
  • 家用、材料实验室、纺织行业温度传感器TOP5权威推荐:温度传
  • Hadoop大数据在2025-2026年和AI智能问数平台的规划与实践
  • IP与子网掩码的关系