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
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: postgres-database: condition: service_healthy
Subscribe to Today I learned
Get the latest posts delivered right to your inbox