Depend on a “ready” service on Docker Compose


Docker TIL

Docker Compose allows specifying dependencies between services with the depends_on directive. For example, when the app service depends on the mysql service, the mysql service will be invoked before the app. However, it does not mean the app will wait until the mysql service becomes ready. If the mysql takes a longer time than the app to become ready, the mysql could be unavailable from the app at some point in the beginning.

To wait to invoke a service until the other service is ready, you can define a health-check command that tells Docker whether the container is ready. The health-check status can be specified as the condition of the dependency’s readiness.

services:
  app:
		build:
      context: .
    command: ['bin/rails', 's', '-p', '3000', '-b', '0.0.0.0']
    volumes:
      - .:/app
    ports:
      - 3000:3000
    depends_on:
      mysql:
        condition: service_healthy # wait until the mysql service becomes healthy

  mysql:
    image: mysql
    volumes:
      - db:/var/lib/mysql
    healthcheck: # check the healthiness with the following configuration
        test: ['CMD', 'mysqladmin', 'ping', '-h', 'localhost', '--user=root', '--password=password']
        interval: 3s
        timeout: 3s
        retries: 5

The example above means the app service will be launched after the state of the mysql service becomes healthy. The healthcheck section is the health check definition for the mysql service. In the depends_on section, condition: service_healthy is the condition of the dependency.

See Also