My container with Springboot is climbing before the container with Mysql finishes climbing

Asked

Viewed 103 times

0

Docker-Compose.yml

version: '3.5'
services:
  marvel-api:
    build: my-api
    container_name: my-api
    depends_on:
      - my-api-bd
    restart: always
    ports:
      - 8080:8080
  my-api-bd:
    build: my-api-bd
    restart: always
    container_name: my-api-bd
    ports: 
      - 3306:3306
    expose: 
      - 3306

The containers begin to rise simultaneously, where the my-api requests access to the bank even before it finishes climbing, causing Exception: java.net.ConnectException: Connection refused (Connection refused) is there a native way of waiting for each other? As you can see, to paleactively solve the problem, I used the restart: always but I feel that this is not a very beautiful solution...

2 answers

1


You can use a script to verify that the desired service is already running. I use the Wait-for a script compatible with Alpine images as a base, Using together with the depends_on you can control the initialization order of the services.

In the example below, the service web1 will run after 11 seconds, as the service web2 theoretically depends on it being running, will only be initialized after the service web1 be performing normally.

version: '3.7'

services:
    web1:
        image: nginx:stable-alpine
        command: sh -c "sleep 11 && nginx -g 'daemon off;'"
        ports:
            - 81:80
        networks:
            - test

    web2:
        build: .
        command: sh -c './wait-for web1:80 -- nginx -g "daemon off;"'
        depends_on: 
            - web1
        ports:
            - 82:80
        networks:
            - test

networks:
    test:

Complete example can be found in this repository github

In the official documentation of Docker-Compose, it also quotes that command depends_on does not guarantee that the application within the specified service is running, it only ensures that the service has been created and even recommends the use of scripts to control the initialization of services that depend on other.

For knowledge purposes only, in version 2 of docker-compose it was possible to control the order by configuration on the docker-compose.yml, using the configuration healthcheck in the database service and using a condition in charge depends_on in the configuration of the api.

0

I noticed that you can added the argument depends_on to your yaml no service my-api but it didn’t solve the problem. What seems to be happening, the container waits for the database container to become active, but the database process has not started yet. You can use the following strategy:

restart: on-failure

That way Docker will try to restart whenever he finds a problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.