python - 在分离之前等待 docker 容器健康检查成功

标签 python docker dockerpy

docker-py 有没有办法在分离容器之前等待健康检查成功?我正在尝试执行以下操作,但问题是 .run() 在健康检查成功之前返回。如果我在 run() 之后尝试 curl elasticsearch 端点,则调用失败。

cls.es = client.containers.run("elasticsearch:7.5.0", auto_remove=True,
                                detach=True, publish_all_ports=True,
                                healthcheck='curl localhost:9200/_cat/health',
                                ports={'9200/tcp': 9200},
                                environment={'discovery.type': 'single-node'})

最佳答案

这似乎完全没有记录,但是通过在源代码中摸索,我想出了一种在继续之前等待健康检查通过的方法。
由于这与您正在检查的图像没有任何关系,因此我使用了一个我熟悉的图像,它有自己的健康检查工具。此方法也适用于其他图像和健康检查方法。

from time import sleep
from docker import APIClient
from docker.models.containers import Container
import docker

def get_health(container: Container):
    api_client = APIClient()
    inspect_results = api_client.inspect_container(container.name)
    return inspect_results['State']['Health']['Status']


client = docker.from_env()
container = client.containers.run(
    'postgres:12',
    environment={'POSTGRES_HOST_AUTH_METHOD': 'trust'},
    detach=True,
    remove=True,
    healthcheck={'test': ['CMD', 'pg_isready', '-U', 'postgres'], 'interval': 100000000},
)
while get_health(container) != 'healthy':
    print(get_health(container))
    sleep(0.1)
print('Container is healthy')
免责声明:
  • 这里没有超时,所以如果健康检查失败,这个过程将永远等待
  • 由于这完全没有记录,我认为有一些原因为什么它不是正确的方法。我很想知道 py-docker 的任何贡献者是否知道此功能发生了什么。

  • 来自贡献者的更新
    我在 Github 问题跟踪器中找到了 this comment,它说:

    The idea is to avoid the proliferation of properties that in turn need to be maintained and may appear in different locations in the attribute dictionary depending on the API version. As a result, we limit the number of quick access attributes to a few essentials. And to that point, I would personally disagree with the notion that a health attribute is essential; most containers do not use healthchecks at all.

    关于python - 在分离之前等待 docker 容器健康检查成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60291082/

    相关文章:

    python - 我尝试使用 exec_run 执行到容器中但不起作用

    python - 我可以在正在运行的 Python 程序中放置一个断点,该程序会下降到交互式终端吗?

    python - SQLAlchemy + 请求异步模式

    Angular:ng-serve 忽略证书

    docker - 当我在 Portainer 中单击 "Update the stack"按钮时执行哪个命令?

    Docker 内部 docker : volume is mounted, 但空

    python - keras.callbacks 中 Tensorboard 导入错误

    python - 在数据框列中对具有相同键的字典求和/相乘

    shell - 使用Dockerfile中的Shell脚本启动多个服务

    分离模式下 exec 命令的 Docker 输出