Search code examples
python-3.xdockerpython-behavedockerpy

Wait for detached container to be running


I am using docker-py to help write some quite complex BDD tests via behave.

I am using containers.run with detach=True since I need to be able to continue my script. A Given step creates a container than is then used by a when step to do something within it, and finally as expected, a then step asserts that the right things were done.

However, I cannot fathom how to have my code wait for the Docker container to be ready to accept data/commands. At the moment, I have an ugly sleep(60) in there which clearly is the wrong way to do it.

How can I wait for the container to be ready?


Solution

  • If the container you're waiting for runs a service that can clearly communicate its state to the outside world (say, a database that refuses or accepts connections), then you can easily build some try-catch functionality in your tests to check whether the container is ready before the tests start.

    However, if there isn't such a thing, you cannot do much besides sleep, because (from Docker's perspective) a container can be ready before the main process inside it is ready (again, a database container could be fully started before the DB process inside it is ready to accept connections, and Docker cannot do much about this).

    A possible approach would be to define a new ENTRYPOINT for the container you're waiting for that puts a file somewhere that your tests could look for. If the file is there, the tests can start, otherwise sleep(1) and look again. Example for an entrypoint.sh (not tested):

    #!/bin/sh
    
    set -e
    
    # run the process you need here
    
    touch /tmp/i-am-ready
    
    exec "$@"
    

    Your tests could then either check for this file in the container directly, or you mount this somewhere as a volume. You would also have to make sure that there still is an attached process after the touch thing, otherwise your container will probably exit 0.