Spring-boot - Docker Compose - Service ready

397 Views Asked by At

I have a docker-compose with 3 services: config-server, cpo-events and cpo-executor. I want that the services start only when config-server is ready because the services need the config files that are in config-server service.

docker-compose.yml:

version: '3.7'
services:
    config-server:
        container_name: cup-config-server
        image: cup-config-server:1.0.0
        expose:
            - 8888
        ports:
            - 8888:8888
        networks:
            - spring-cloud-network
        healthcheck:
            test: ["CMD", "curl", "-f", "http://localhost:8888/cpo-executor/dev"]
            interval: 30s
            timeout: 10s
            retries: 5
    cpo-events:
        container_name: cpo-events-kafka
        image: cpo-events-kafka:1.0.0
        expose:
            - 8878
        ports:
            - 8878:8878
        networks:
            - spring-cloud-network
        depends_on:
            - config-server
        links: 
            - config-server
    cpo-executor:
        container_name: cpo-executor
        image: cpo-executor:1.0.0
        expose:
            - 8879
        ports:
            - 8879:8879
        networks:
            - spring-cloud-network
        depends_on:
            - config-server
        links: 
            - config-server
networks:
    spring-cloud-network:
        driver: bridge

Depends_on, links, healthcheck, nothing is guaranteeing the two services(cpo-executor, cpo-event) to start only after config-server is ready.

1

There are 1 best solutions below

2
On

If you are testing the services locally, then you can add an entry point script

#!/usr/bin/env bash

wait_single_host() {
  local host=$1
  shift
  local port=$1
  shift

  echo "==> Check host ${host}:${port}"
  while ! nc ${host} ${port} > /dev/null 2>&1 < /dev/null; do echo "   --> Waiting for ${host}:${port}" && sleep 1; done;
}

wait_all_hosts() {
  if [ ! -z "$WAIT_FOR_HOSTS" ]; then
    local separator=':'
    for _HOST in $WAIT_FOR_HOSTS ; do
        IFS="${separator}" read -ra _HOST_PARTS <<< "$_HOST"
        wait_single_host "${_HOST_PARTS[0]}" "${_HOST_PARTS[1]}"
    done
  else
    echo "IMPORTANT : Waiting for nothing because no $WAIT_FOR_HOSTS env var defined !!!"
  fi
}

wait_all_hosts
sleep 60

bash -c "/usr/local/bin/docker-entrypoint $*"

You can check the full example usage here. It solves the same problem but for different use case with docker-compose version 3.7