Skip to content
How to wait for container X before starting Y using docker-compose healthcheck
Branch: master
Clone or download
Latest commit 2542734 Aug 13, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.travis.yml Add endpoint test Aug 13, 2019
LICENSE Initial commit Mar 2, 2017
README.md Update README Mar 18, 2019
README_JP.md Update README_JP Aug 2, 2018
demo.gif Update demo gif Aug 2, 2018
docker-compose.yml Fix for recent version of Kong Mar 18, 2019

README.md

docker-compose-healthcheck The blog of Peter Evans: How to Wait for Container X Before Starting Y

Build Status

Since docker-compose version 2.1 file format the healthcheck parameter has been introduced. This allows a check to be configured in order to determine whether or not containers for a service are "healthy."

How can I wait for container X before starting Y?

This is a common problem and in earlier versions of docker-compose requires the use of additional tools and scripts such as wait-for-it and dockerize. Using the healthcheck parameter the use of these additional tools and scripts is often no longer necessary.

Waiting for PostgreSQL to be "healthy"

A particularly common use case is a service that depends on a database, such as PostgreSQL. We can configure docker-compose to wait for the PostgreSQL container to startup and be ready to accept requests before continuing.

The following healthcheck has been configured to periodically check if PostgreSQL is ready using the pg_isready command. See the documentation for the pg_isready command here.

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

If the check is successful the container will be marked as healthy. Until then it will remain in an unhealthy state. For more details about the healthcheck parameters interval, timeout and retries see the documentation here.

Services that depend on PostgreSQL can then be configured with the depends_on parameter as follows:

depends_on:
  postgres-database:
    condition: service_healthy

Waiting for PostgreSQL before starting Kong

In this complete example docker-compose waits for the PostgreSQL service to be "healthy" before starting Kong, an open-source API gateway. It also waits for an additional ephemeral container to complete Kong's database migration process.

Test it out with:

docker-compose up -d

Wait until all services are running:

Demo

Test by querying Kong's admin endpoint:

curl http://localhost:8001/

License

MIT License - see the LICENSE file for details

You can’t perform that action at this time.