RabbitMq refuses connection when run in docker


My docker-compose file looks like this:

version: '2' services: explore: image: explore build: context: ./Explore dockerfile: VsDockerfile environment: - "ElasticUrl=http://localhost:9200" - "RabbitMq/Host=localhost" - "RabbitMq/Username=guest" - "RabbitMq/Password=guest" networks: - localnet elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:5.4.3 container_name: elasticsearch environment: - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ports: - 9200:9200 volumes: - ./esdata:/usr/share/elasticsearch/data networks: - localnet rabbit: image: rabbitmq:3.6.7-management hostname: rabbit ports: - 15672:15672 - 5672:5672 networks: - localnet networks: localnet: external: name: localnet

If I type <a href="http://localhost:15672" rel="nofollow noreferrer">http://localhost:15672</a> in the browser, I get the rabbitmq interface, but if I tries to connect from my Explore project like this:

public SqlToRabbitProcessor(SqlToRabbitRepository sqlToRabbitRepository) { _sqlToRabbitRepository = sqlToRabbitRepository; var factory = new ConnectionFactory { HostName = Environment.GetEnvironmentVariable("RabbitMq/Host"), UserName = Environment.GetEnvironmentVariable("RabbitMq/Username"), Password = Environment.GetEnvironmentVariable("RabbitMq/Password") }; var rabbit = factory.CreateConnection(); channel = rabbit.CreateModel(); }

Then it breaks in the line

var rabbit = factory.CreateConnection();

with the error saying

ExtendedSocketException: Connection refused System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

ConnectFailureException: Connection failed RabbitMQ.Client.EndpointResolverExtensions.SelectOne(IEndpointResolver resolver, Func selector)

BrokerUnreachableException: None of the specified endpoints were reachable RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)


As my comment under the question suggested, it's because the "localhost" defined in the web application part is it's containers localhost, and not the docker host..

just needed to change

- "ElasticUrl=http://localhost:9200" - "RabbitMq/Host=localhost"


- "ElasticUrl=http://elasticsearch:9200" - "RabbitMq/Host=rabbit"


I had the same issue with docker-compose.

I solved it by with hostname:

rabbit: hostname: rabbit command: sh -c "rabbitmq-plugins enable rabbitmq_management; rabbitmq-server" image: rabbitmq environment: RABBITMQ_DEFAULT_USER: admin RABBITMQ_DEFAULT_PASS: admin ports: - 5672:5672 - 15672:15672