pythondockerdockerpy

Wait for Docker container to become running using Python SDK


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?


Solution

  • 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