Refused connection to RabbitMQ when using docker link

南楼画角 提交于 2020-05-29 07:26:07

问题


I have a microservices application which has two services and a rabbit mq used as a message queue for communication between them. Now, I want to deploy them on docker. I have the following code in the docker-compose.yml file:

version: "3" services:

  rabbitmq:
    build: ./Rabbit
    hostname: "rabbitmq"
    container_name: "rabbitmq"
    environment:
      RABBITMQ_ERLANG_COOKIE: "cookie"
      RABBITMQ_DEFAULT_USER: "user"
      RABBITMQ_DEFAULT_PASS: "pass"
      RABBITMQ_DEFAULT_VHOST: "/"
    ports:
      - "15672:15672"
      - "5672:5672"
    # labels:
    #   NAME: "rabbit1"
    volumes:
    - "/opt/rabbitmq:/var/lib/rabbitmq"

  service1:
    build: ./service1
    deploy:
      replicas: 5
      restart_policy:
        condition: on-failure
      resources:
        limits:
          cpus: "0.1"
          memory: 50M
    ports:
      - "8181:80"
    depends_on:
      - rabbitmq
    links:
     - rabbitmq
    networks:
      - webnet

So, here I build the RabbitMQ image in a container and then link this container to the container of service1. Since service1 one is an ASP.NET Core Web API, I use the following setup to connect to the message queue:

//Establish the connection
            var factory = new ConnectionFactory
            {
                HostName = "rabbitmq",
                Port = 5672,
                UserName = "user",
                Password = "pass",
                VirtualHost = "/",
                AutomaticRecoveryEnabled = true,
                NetworkRecoveryInterval = TimeSpan.FromSeconds(15)
            };

But when I try to run docker-compose up, I receive the following error message:

Unhandled Exception: RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address

Maybe I have a mistake in the HostName but I am not sure how to correct it.


回答1:


There are two problems that need to be fixed:

  1. the two services do not belong to the same network so you need to add the rabbitmq service to the webnet network or create a new network for the two services

  2. rabbitmq may take some time to become fully available (i.e. to listen to the 5672 port) so you need to make the service1 service to wait for the rabbitmq service; see this question about this issue.



来源:https://stackoverflow.com/questions/44802594/refused-connection-to-rabbitmq-when-using-docker-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!