How to wait for a container to be “ready” before starting another container, using Docker Compose

Edgar Gonzalez
2 min readApr 9, 2016

--

Currently I’m working on dockerizing a Sinatra app that access ElasticSearch. Recently I faced an issue when I tried to run the integration tests inside the container. The docker-compose files are:

I’m using the version 2 of the compose file format which allow you to reuse services. And I have a Makefile like this:

So, the issue was that the tests needs to wait until ElasticSearch is ready to accept connections, one dirty workaround is add an sleep to the test command, for instance the Makefile will be:

Definitely this is not the best approach. So, I started searching for a better option and I found Docker-Wait, an utility that blocks until another container is accepting TCP connections, and errors-out if it cannot connect within a given timeout. Now my docker-compose and Makefile files are:

As you can notice I added a new “wait” service to the docker-compose file that depends on the ElasticSearch container and I’m supplying a TARGET environment variable with the host and port to check. In the Makefile I added the line #8, which execute the wait container and blocks until ElasticSearch is ready to accept connections.

Because of the TARGET env var accepts a comma-separated list of <host>:<port> tuples, you can use one Docker-Wait container to wait for multiple containers.

This approach works very well, and I’ll be using it until the feature is added to docker compose (here is the feature request)

--

--

Edgar Gonzalez

Current iteration: Director of Software Engineering @StreetEasy/@Zillow | Previously: Director DevOps & Data @BlueApron · @Piictu (@TechStars) · gonzalez.io