docker-compose wait on other service before build

20 min read

To wait for another service to be up and running before building a service in Docker Compose, you can use the depends_on and healthcheck options.

First, add a healthcheck option to the service you want to wait for. For example, if you want to wait for a PostgreSQL database to be up and running before building a Django web app:

version: '3'
services:
  db:
    image: postgres
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 5s
      timeout: 5s
      retries: 5

  web:
    build: .
    depends_on:
      db:
        condition: service_healthy

The healthcheck option in the db service specifies the command to check if the database is ready (pg_isready -U postgres), and the interval, timeout, and retries options define how often and how many times to run the check before considering the service healthy.

Next, add a depends_on option to the service that needs to wait for the other service to be ready (web in this case). The condition: service_healthy option specifies that the service should wait until the db service is healthy before starting:

    depends_on:
      db:
        condition: service_healthy

With these settings, Docker Compose will start the db service, run the health check command, and wait until the service is healthy before starting the web service.

Note that depends_on only ensures that the service starts after the service it depends on. It doesn't guarantee that the dependent service is actually ready to accept connections. The healthcheck option is necessary to ensure that the service is actually up and running before proceeding.