4

Using the docker module for Python, you can start a detached container like this:

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

I need to wait for this container to be running (ie container.status == 'running'). If you check the status immediately after creating the container, it will report this, meaning that it is not yet ready:

>>> container.status
"created"

The API does provide a wait() method, but this only waits for termination statuses like exit and removed: https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.Container.wait.

How can I wait until my container is running using docker for Python?

Migwell
  • 18,631
  • 21
  • 91
  • 160

1 Answers1

9

You can use a while loop with a timeout

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
Iduoad
  • 895
  • 4
  • 15
  • 10
    In my experience, `container.status` does not get updated from `'created'` to `'running'` when the container starts running. You should use `docker.containers.get(container.id)` to get the latest status. – bjschoenfeld Jan 14 '21 at 05:50
  • 6
    @bjschoenfeld, to update container status you can also use `container.reload()` instead of `docker.containers.get(container.id)`. – vvzh Nov 09 '21 at 23:09