Connecting to RabbitMQ container with docker-compose

前端 未结 2 708
一个人的身影
一个人的身影 2021-02-05 19:45

I want to run RabbitMQ in one container, and a worker process in another. The worker process needs to access RabbitMQ.

I\'d like these to be managed through docker-

2条回答
  •  爱一瞬间的悲伤
    2021-02-05 20:01

    Aha! I fixed it. @Ijaz was totally correct - the RabbitMQ service takes a while to start, and my worker tries to connect before it's running.

    I tried using a delay, but this failed when the RabbitMQ took longer than usual.

    This is also indicative of a larger architectural problem - what happens if the queuing service (RabbitMQ in my case) goes offline during production? Right now, my entire site fails. There needs to be some built-in redundancy and polling.

    As described this this related answer, we can use healthchecks in docker-compose 3+:

    version: "3"
    
    services:
    
      rabbitmq:
        image: rabbitmq
        command: rabbitmq-server
        expose:
          - 5672
          - 15672
        healthcheck:
          test: [ "CMD", "nc", "-z", "localhost", "5672" ]
          interval: 5s
          timeout: 15s
          retries: 1
    
      worker:
        image: worker
        restart: on-failure
        depends_on:
          - rabbitmq
    

    Now, the worker container will restart a few times while the rabbitmq container stays unhealthy. rabbitmq immediately becomes healthy when nc -z localhost 5672 succeeds - i.e. when the queuing is live!

提交回复
热议问题