等待Docker容器使用Python SDK运行

问题描述

使用Python的docker模块,您可以像这样启动一个分离的容器:

import docker
client = docker.from_env()
container = client.containers.run(some_image,detach=True)

我需要等待此容器为running(即container.status == 'running')。如果您在创建容器后立即检查状态,它将报告此情况,表示该容器尚未准备就绪:

>>> container.status
"created"

API确实提供了wait()方法,但这仅等待exitremovedhttps://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.Container.wait之类的终止状态。

我如何才能等到running的容器在Python中使用docker

解决方法

您可以使用带有超时的while循环

import docker
from time import sleep 

client = docker.from_env()
container = client.containers.run(some_image,detach=True)

timeout = 120
stop_time = 3
elapsed_time = 0
while container.status != 'running' and elapsed_time < timeout:
    sleep(stop_time)
    elapsed_time += stop_time
    continue