Checking if the Elasticsearch service of a Docker container is ready

Published on 2020-09-08 • Modified on 2020-09-08

This is the third part of the "wait-for-this-service" series (check the links below the code). In the last snippet, we saw how to wait for MySQL. In this project, after I load the data in the database, I have to index them in Elasticsearch, so checking if MySQL is ready is not enough as the Elasticsearch initialization time can be longer than MySQL. In this case, we will take advantage of Elasticsearch's cluster API. We have a dedicated parameter wait_for_status that forces the API to return a success status only when the cluster gains at least this status. That's very convenient because it's precisely what we need for our "wait" bash script. If Elasticsearch is not available at all the curl returns a failure status, and if it is available, it returns a success status only if the cluster is yellow or green. In my Makefile, I call this script just after the fixtures' loading. It allows Elasticsearch to continue its initialization while the data are being loaded.

# If called very early the curl will receive an "empty" response and a failing status
# As soon as Elasticsearch can process the command, it will return a success status
# as soon as the cluster is yellow or green
until curl 'localhost:9209/_cluster/health?wait_for_status=yellow&timeout=30s'; do
  >&2 echo "Elastisearch is unavailable - waiting for it... 😴"
  sleep 1

 More on Stackoverflow   Read the doc  More on the web  Random snippet