DEV Community

Ryo Kuroyanagi
Ryo Kuroyanagi

Posted on

Frequently used 2 healthcheck recipes for docker-compose dependency resolution

These days, many developers are using docker-compose to build system on our local machines. If each container does not depend on each other, the system is simple. However, we usually have dependent and dependency containers within our docker-compose networks. I'm sharing the most basic cases of dependent-dependency pattern and how to boot containers in a order that we expect.

Basics: Docker healthcheck

Docker has healthcheck functionality. The rules can be written in our Dockerfile or docker-compose. In docker-compose, it is written like following. The server container relies on db container. db should have healthcheck section and the condition. server should have db in the depends_on and the condition underneath to make sure that it boots after the db container gets health status.

services:
  server:
    image: your_server_image
    depends_on:
      db: 
        condition: service_healthy
  db:
    image: your_db_image
    healthcheck:
      test: ... # Command to check health.
      interval: 5s # Interval between health checks.
      timeout: 5s # Timeout for each health checking.
      retries: 20 # Hou many times retries.
      start_period: 10s # Estimated time to boot.
Enter fullscreen mode Exit fullscreen mode

Case 1: Server depends on MySQL

Maintain server and MySQL containers in the same docker-compose runtimes is a very common pattern. The server must be booted after the MySQL container gets ready if you want to do something like table migrations when the server container booted. Pinging with mysqladmin to MySQL server in the db container, we can check if MySQL is ready. The MySQL server runs on localhost in the contianer, the host -h parameter must be localhost. The password is the one you set in the environment section with the MYSQL_ROOT_PASSWORD parameter.

  db:
    image: mysql:8.0.26
    ports:
      - 3316:3306
    environment:
      MYSQL_DATABASE: yourdb
      MYSQL_ROOT_PASSWORD: pass
    healthcheck:
      test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost", "-uroot", "-ppass"]
      interval: 5s
      timeout: 5s
      retries: 20
Enter fullscreen mode Exit fullscreen mode

Case 2: Server depends on another server

If we have more than 1 server, the servers may depends on others. e.g. In an image detection service system, one main server for user access and another server for image detection by machine learning. For the case, self-pinging should be the simplest solution. For the server runs on localhost and 8080 port in the container, curl command to ping should be like the below.

  image_detection:
    image: your_image
    ports:
      - 8082:8080
    healthcheck:
      test: "curl -f localhost:8080"
      interval: 5s
      timeout: 5s
      retries: 20
Enter fullscreen mode Exit fullscreen mode

Top comments (0)