0

I have a microservice application that uses RabbitMQ. How can I run the RabbitMQ consumer from the application backend container only after the RabbitMQ is up and running. My compose file is as below.

certichain_backend:
    depends_on:
      - rabbitmq

    working_dir: /app/backend/src 
    command: sh sleep 20 & nohup node /app/backend/src/services/amqp_consumer.js && npm run start;

rabbitmq:
     image: "rabbitmq:3-management"
     hostname: "rabbitmq"
     restart: always
     expose:
       - 15672
       - 5672
     labels:
       NAME: "rabbitmq"
     volumes:
       - ./rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf
                

I have given the backend the 'depends_on' to rabbitmq. But what I have observed is, the rabbitmq container starting process is initiated. But the backend container is not waiting for the rabbitmq container to up completely. My consumer is running along with the backend. So the consumer cannot connect to amqp server since it is not running at that moment. Thus I added a sleep parameter. So that it gets some time while rabbitmq to bringing up.

This method is very inconsistent. I'm sure this is not the right way to achieve this.

Muhzin
  • 390
  • 6
  • 19

1 Answers1

2

In your nodejs code you can add feature to terminate process with exit 1, if rabbitmq container is unreachable.

rabbitmq.connect('rabbitmq://guest:guest@rabbitmq',{})
  .then(function(connection){
     console.log('Rabbitmq connection established');
     // other code here
   })
   .catch(function(errror) {
     console.error('%s while dialing rabbitmq', error.message);
     process.exit(1);
   });

and in docker-compose file you can add restart: on-failure, so, if rabbitmq container have not started, nodejs application fails to start and is restarted until rabbitmq container is ready.

It can be worth to make rabbitmq connection establishment one of first actions nodejs application does - so, if there is no rabbitmq, nothing starts.

vodolaz095
  • 6,680
  • 4
  • 27
  • 42
  • 1
    To add some weight to this, I think that it is actually the correct approach. Containers are fast and cheap and the right way to deal with connection problems is to kill the container -- it's much easier than complex `back-off and retry` logic. Docker agrees too: https://docs.docker.com/compose/startup-order/ . Though, this sample code should have been written with async...await, this isn't the 90's :) – Software Engineer Feb 01 '21 at 06:37