How can I wait for a docker container to be up and running?

Gravis picture Gravis · Jan 17, 2014 · Viewed 76.6k times · Source

When running a service inside a container, let's say mongodb, the command

docker run -d myimage

will exit instantly, and return the container id. In my CI script, I run a client to test mongodb connection, right after running the mongo container. The problem is: the client can't connect because the service is not up yet. Apart from adding a big sleep 10in my script, I don't see any option to wait for a container to be up and running.

Docker has a command wait which doesn't work in that case, because the container doesn't exist. Is it a limitation of docker?

Answer

superhero picture superhero · Nov 4, 2015

Found this simple solution, been looking for something better but no luck...

until [ "`/usr/bin/docker inspect -f {{.State.Running}} CONTAINERNAME`"=="true" ]; do
    sleep 0.1;
done;

or if you want to wait until the container is reporting as healthy (assuming you have a healthcheck)

until [ "`/usr/bin/docker inspect -f {{.State.Health.Status}} CONTAINERNAME`"=="healthy" ]; do
    sleep 0.1;
done;