Search code examples
dockerelasticsearchdocker-composeelasticsearch.net

ElasticSearch, ElasticSearch.Net and dockercompose with error cannot assign requested address site


I am trying to create a sample application with a .Net core web application, .Net core API and ElasticSearch. Each are in their own docker containers. I can't get the API to communicate with the ElasticSearch docker container.

Here is my docker-compose file:

version: '3.4'

services:
  webfrontend:
    image: ${DOCKER_REGISTRY-}webfrontend
    build:
      context: .
      dockerfile: WebFrontEnd/Dockerfile
    depends_on:
        - mywebapi
    networks:
        - esnetwork

  mywebapi:
    image: ${DOCKER_REGISTRY-}mywebapi
    build:
      context: .
      dockerfile: MyWebAPI/Dockerfile
    depends_on:
        - es01
    networks:
        - esnetwork

  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.1
    container_name: es01
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - discovery.type=single-node
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data01:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
      - 9300:9300
    networks:
        - esnetwork

volumes:
  data01: 
    driver: local

networks:
    esnetwork:
        driver: bridge

The API code I am using is:

[HttpGet]

public string Get()
{
    //var settings = new ConnectionConfiguration(
    //    new Uri("http://localhost:9200"));
    var settings = new ConnectionConfiguration();

    var lowlevelClient = new ElasticLowLevelClient(settings);
    var indices = lowlevelClient.Cat.Health<BytesResponse>();
    //string responseStream = indices.Body;
    return $"Number of cats = ";
}

The error I get is "cannot assign requested address site".

I can hit ElasticSearch using the following in cmd:

curl -X GET http://localhost:9200/_cat/health

What am I doing wrong?


Solution

  • All services in docker compose are connect to a common network by default (in your case they are even connected to a common network esnetwork). The service name is a DNS name which you can use to connect from one container to another. In your case you would have to configure your webapi to connect to http://es01:9200 not a localhost. You could set it using environment variables or whatever way is convenient for you. For example :

    var uri = new Uri("http://es01:9200");
    var settings = new ConnectionConfiguration(uri);
    

    or

    string elasticHost = Environment.GetEnvironmentVariable("ELASTIC_HOST");
    var uri = new Uri(elasticHost);
    var settings = new ConnectionConfiguration(uri);
    

    and set environment variable ELASTIC_HOST in docker-compose for your webapi service :

    environment:
          - ELASTIC_HOST=es01