Elastcsearch client - javascript connection error

Hi,

I am running a 7.17 Elasticsearch and kibana services using docker compose with xpack security disabled (local env). I am developing an express application for some data manipulation so trying to use the Elasticsearch client for ingesting data. I am getting the below connection error for the basic cluster health check

Here is the express router code
Router.js

const express = require('express');
const router = express.Router();
const elasticsearch = require('@elastic/elasticsearch');

const esclient = new elasticsearch.Client({  
    node: 'https://localhost:9200/',
    //'https://[username]:[password]@[server]:[port]/'
    auth: {
        username: 'elastic',
        password: 'changeme'
    }                
});

 /* This operation health of es */
router.get('/health',(req,res) => {
    console.log("I am here");
    esclient.cluster.health({},(err,resp,status) => {  
      if(err)
      {  console.log("-- Client Health ERROR--",err);
      }else{
         console.log("-- Client Health --",resp);
         //res.send({resp});
      } 
    });
 }); 
module.exports = router;

Index.js

const express = require('express');
const app = express();
const routes = require('./esRouter');

var path = require('path');
let port = process.env.PORT || 4500;

app.get('/',(req,res) => {
    res.send('Hello check localhost:4500/health for ES connectivity');
});

app.get('/home', (req, res) => {
    res.send('Home Page');
});

app.get('/health', routes);

app.listen(port,()=>console.log(`Running nodeapp on port ${port}!`))

Error I am getting on the console

NodeApp % node index.js
Running nodeapp on port 4500!
I am here
NodeApp/node_modules/@elastic/transport/lib/Transport.js:525
                            : new errors_1.ConnectionError(error.message, result);
                              ^

ConnectionError: 4413556096:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:

    at SniffingTransport.request (NodeApp/node_modules/@elastic/transport/lib/Transport.js:525:31)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Cluster.health (NodeApp/node_modules/@elastic/elasticsearch/lib/api/api/cluster.js:183:16) {
  meta: {
    body: undefined,
    statusCode: 0,
    headers: {},
    meta: {
      context: null,
      request: {
        params: {
          method: 'GET',
          path: '/_cluster/health',
          querystring: '',
          headers: {
            'user-agent': 'elastic-transport-js/8.0.2 (darwin 21.3.0-arm64; Node.js v16.14.0)',
            'x-elastic-client-meta': 'es=8.1.0,js=16.14.0,t=8.0.2,hc=16.14.0',
            accept: 'application/vnd.elasticsearch+json; compatible-with=8,text/plain'
          }
        },
        options: [Function (anonymous)],
        id: 1
      },
      name: 'elasticsearch-js',
      connection: Connection {
        url: <ref *1> URL {
          [Symbol(context)]: URLContext {
            flags: 400,
            scheme: 'https:',
            username: '',
            password: '',
            host: 'localhost',
            port: 9200,
            path: [Array],
            query: null,
            fragment: null
          },
          [Symbol(query)]: URLSearchParams {
            [Symbol(query)]: [],
            [Symbol(context)]: [Circular *1]
          }
        },
        tls: null,
        id: 'https://localhost:9200/',
        timeout: 30000,
        headers: { authorization: 'Basic ZWxhc3RpYzpjaGFuZ2VtZQ==' },
        deadCount: 0,
        resurrectTimeout: 0,
        _openRequests: 0,
        weight: 1000,
        pool: <ref *2> Pool {
          _events: [Object: null prototype] {},
          _eventsCount: 0,
          _maxListeners: undefined,
          [Symbol(kCapture)]: false,
          [Symbol(queue)]: FixedQueue {
            tail: [FixedCircularBuffer],
            head: [FixedCircularBuffer]
          },
          [Symbol(closed promise)]: null,
          [Symbol(closed resolve)]: null,
          [Symbol(destroyed)]: false,
          [Symbol(clients)]: [ [Client], [Client] ],
          [Symbol(needDrain)]: false,
          [Symbol(queued)]: 0,
          [Symbol(onDrain)]: [Function: onDrain],
          [Symbol(onConnect)]: [Function (anonymous)],
          [Symbol(onDisconnect)]: [Function (anonymous)],
          [Symbol(onConnectionError)]: [Function (anonymous)],
          [Symbol(stats)]: PoolStats { [Symbol(pool)]: [Circular *2] },
          [Symbol(connections)]: 256,
          [Symbol(url)]: URL {
            [Symbol(context)]: [URLContext],
            [Symbol(query)]: [URLSearchParams]
          },
          [Symbol(options)]: {
            keepAliveTimeout: 600000,
            keepAliveMaxTimeout: 600000,
            keepAliveTimeoutThreshold: 1000,
            pipelining: 1,
            maxHeaderSize: 16384,
            headersTimeout: 30000,
            bodyTimeout: 30000,
            connect: [Function: connect]
          },
          [Symbol(factory)]: [Function: defaultFactory]
        },
        [Symbol(status)]: 'alive',
        [Symbol(ca fingerprint)]: null,
        [Symbol(diagnostics)]: Diagnostic {
          _events: [Object: null prototype] {},
          _eventsCount: 0,
          _maxListeners: undefined,
          [Symbol(kCapture)]: false
        },
        [Symbol(event emitter)]: EventEmitter {
          _events: [Object: null prototype] {},
          _eventsCount: 0,
          _maxListeners: undefined,
          [Symbol(kCapture)]: false
        }
      },
      attempts: 3,
      aborted: false
    },
    warnings: [Getter]
  }
}

I looked into the ssl and tls configurations but those things all come with xpack enabled since it my local env I am trying to figure out how to make my client work without certs. Any help is appreciated.

Hello! From the logs it looks like you are using the wrong version of the client. If you are using Elasticsearch 7.17, then you should use the client 7.17.

Are you running the node.js application from docker as well? Can you share your docker compose configuration?

Here is my Docker compose file. I will try the other client version 7.17

Docker compose

version: '2.2'
services:
  node01:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.0
    container_name: node01
    environment:
      - node.name=node01
      - cluster.name=es-cluster-7
      - discovery.type=single-node
      - "ES_JAVA_OPTS=-Xms128m -Xmx128m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - es-data01:/usr/share/elasticsearch/data
      - ./synonyms.txt:/usr/share/elasticsearch/config/analysis/synonyms.txt
      - .:/mnt
    ports:
      - 9200:9200
    networks:
      - es-network
    entrypoint: /mnt/docker-entrypoint-es.sh

  kibana:
    image: docker.elastic.co/kibana/kibana:7.17.0
    environment:
      ELASTICSEARCH_HOSTS: http://node01:9200
    ports:
      - 5601:5601
    networks:
      - es-network
    depends_on:
      - node01

volumes:
  es-data01:
    driver: local
  
networks:
  es-network:
    driver: bridge

I tried the client version 7.17 and its a different err this time

-- Client Health ERROR-- ConnectionError: write EPROTO 4381951360:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:

    at ClientRequest.onError (NodeApp/node_modules/@elastic/elasticsearch/lib/Connection.js:123:16)
    at ClientRequest.emit (node:events:520:28)
    at TLSSocket.socketErrorListener (node:_http_client:442:9)
    at TLSSocket.emit (node:events:520:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  meta: {
    body: null,
    statusCode: null,
    headers: null,
    meta: {
      context: null,
      request: [Object],
      name: 'elasticsearch-js',
      connection: [Object],
      attempts: 3,
      aborted: false
    }
  }
}

Are you seeing any issue in the docker compose logs as well?
It looks like you are trying to use HTTPS while you haven't configured Elasticsearch to do so.
Take a look at our docs to learn how to configure it.
Otherwise, you can directly start working with the Elastic stack version 8, which has security enabled by default!

I have to stick to the 7.17 version as of now.

client % node elasticsearch.js
Cannot connect to elasticsearch
ResponseError: Response Error
    at onBody (NodeApp/node_modules/@elastic/elasticsearch/lib/Transport.js:367:23)
    at IncomingMessage.onEnd (NodeApp/node_modules/@elastic/elasticsearch/lib/Transport.js:291:11)
    at IncomingMessage.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  meta: {
    body: '',
    statusCode: 400,
    headers: {
      'x-elastic-product': 'Elasticsearch',
      warning: '299 Elasticsearch-7.17.0-bee86328705acaa9a6daede7140defd4d9ec56bd "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."',
      'content-type': 'application/json; charset=UTF-8',
      'content-length': '259'
    },
    meta: {
      context: null,
      request: [Object],
      name: 'elasticsearch-js',
      connection: [Object],
      attempts: 0,
      aborted: false
    }
  }
}

I tried with the http and got this minimal security features that needs to be done

I will give this one a try before I hit the next version.

I am trying to enable the security features(minimal security) any docs on how to run the [ elasticsearch-setup-passwords ] utility in docker-compose file.

This document should tell you all you need.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.