/ docker

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

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

Manu S Ajith

Manu S Ajith

Tech Entrepreneur, dating Elixir, in long-term ❤️ w/ Ruby, had multiple one night stands w/ Go. Into functional paradigms DDD/CQRS/EventSourcing architecture these days. @manusajith on the interwebs

Read More