Home > front end >  Unable to establish connection with elasticsearch 8.1 (java)
Unable to establish connection with elasticsearch 8.1 (java)

Time:05-10

I have elasticsearch 8.1 running in docker with this docker compose file:

version: '3.7'

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.1.0
    container_name: es-node
    environment:
     - xpack.security.enabled=false
     - discovery.type=single-node
    volumes:
      - ./elastic-data:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    cap_add:
     - IPC_LOCK
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nofile:
        soft: 65536
        hard: 65536
  kibana:
    image: docker.elastic.co/kibana/kibana:8.1.0
    container_name: kibana
    environment:
      - ELASTICSEARCH_HOST=http://localhost:9200
    ports:
      - 5601:5601
    depends_on:
      - elasticsearch

I'm trying to make a simple GET request to the es cluster using the org.elasticsearch.client.RestClient.

Request:

        Request request = new Request("GET", "_cluster/health");

        try {
            return restClient.performRequest(request).toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

Rest client initialisation:

        var hosts = buildClusterHosts(transportAddresses);
        restClient = RestClient.builder(hosts).build();

        var esTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        elasticsearchClient = new ElasticsearchClient(esTransport);

Main method:

        var es = ElasticEightClient.builder()
                .transportAddresses("localhost:9200")
                .isElasticSniffEnabled(true)
                .build();


        System.out.println("Started elasticsearch with health: "   es.getHealth());

buildClusterHosts() method is correctly building an array of HttpHost (in this case only one) and provides it to the rest client builder.

In theory this should be enough, but I keep getting Caused by: java.net.ConnectException: Timeout connecting to [/172.20.0.2:9200] and I'm not sure why?

CodePudding user response:

Tldr;

It seems you are confusing the Transport port and the Rest Api port of Elasticsearch.

To Fix

You will first need to expose the port of the transport layer, which is 9300 by default

services:
  elasticsearch:
    ports:
      - 9300:9300

Then update the main method

var es = ElasticEightClient.builder()
         .transportAddresses("localhost:9200")
         .isElasticSniffEnabled(true)
         .build();


System.out.println("Started elasticsearch with health: "   es.getHealth());
  • Related