Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control services start-up sequence in docker-compose.yml file?

Tags:

devops

Here is my docker-compose.yml file

    version: '3'
    services:
      mongodb:
        image: hedge-mongo:1.0
        container_name: mongodb
        ports:
          - "27017:27017"
        networks:
          - appNetwork
      service-A:
        image: service-A:1.0
        container_name: service-A
        ports:
          - "3030:3030"
        networks:
          - appNetwork
        depends_on:
          - mongodb   
      service-B:
        image: service-B:1.0
        container_name: service-B
        ports:
          - "4200:4200"
        networks:
          - appNetwork
      service-C:
        image: service-C:1.0
        container_name: service-C
        ports:
          - "8082:8082"
       networks:
      - appNetwork 
   networks:
    appNetwork:
    external: true

In above file service-A and service-C are trying to connect to MongoDB Issue: In above file service-A and service-C are getting connected to MongoDB before MongoDB is up so, I want to run service-A and service-C after MongoDB is up completely. I tried adding depends-on for service-A and service-C

service-A:
    image: service-A:1.0
    container_name: service-A
    ports:
      - "3030:3030"
    networks:
      - appNetwork
    depends_on:
      - mongodb   

  service-C:
    image: service-C:1.0
    container_name: service-C
    ports:
      - "8082:8082"
    networks:
      - appNetwork 
    depends_on:
      - mongodb 

still, it did not work out sometimes it works sometimes it doesn't so it's not reliable. I want to make sure my other services are up only after MongoDB is up.

like image 249
Shraddha Agarwal Avatar asked Dec 11 '25 11:12

Shraddha Agarwal


1 Answers

that is a race condition, you're services is trying to start at the same time, thats why you got a result of sometimes it success and sometimes its not.. here an example on how to solve the race condition..

example 1

example 2

like image 81
Fendi jatmiko Avatar answered Dec 13 '25 09:12

Fendi jatmiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!