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/