Making dependent services wait till containers are healthy using docker health check

Using the health check option provided by docker we can make containers wait till the dependent containers are online and healthy

A typical use case for adding a health check in docker is when you want to wait for your database container to be online before starting a web app container.

Docker compose provides an easy option for doing a health check on your dependent container and even wait for the container to online before spinning up the other dependent containers.

Making your web container wait till your database container is healthy.

Let's assume your web application is using PostgreSQL as the database, and you want to make sure that your PostgreSQL container is up and running before you start your web app.

First, we configure docker to do a health check on our PostgreSQL container using the pg_isready command.

healthcheck:
  test: ["CMD-SHELL", "pg_isready -U postgres"]
  interval: 30s
  timeout: 30s
  retries: 3
  

Our PostgreSQL container will be marked as healthy only if the pg_isready command is successful and will remain unhealthy till it returns success.

Next, we have to make our web app container depend on the health status of our PostgreSQL container. For this, we will use the depends_on option.

depends_on:
  postgres-database:
    condition: service_healthy 

References:

Docker health check docs
pg_isready doc
Docker depends_on doc