Lazov
Lazov

Reputation: 1476

Refused connection to RabbitMQ when using docker link

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.

Upvotes: 3

Views: 4421

Answers (1)

Constantin Galbenu
Constantin Galbenu

Reputation: 17713

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.

Upvotes: 2

Related Questions