无法从我的Nodejs应用程序连接Elasticsearch:连接ECONNREFUSED 127.0.0.1:9200

时间:2020-11-01 08:43:23

标签: node.js docker elasticsearch

我无法从我的NodeJS应用程序连接到Elasticsearch泊坞服务器。

我的代码

这是我的 docker-compose文件

version: "3.7"
services:
  backend:
    container_name: vstay-api
    ports:
      - "4000:4000"
    build:
      context: .
      dockerfile: Dockerfile
    env_file:
      - ./.env
    environment:
      - DB_URI=mongodb://mongo:27017/vstay-db
      - DB_HOST=mongo
      - DB_PORT=27017
    restart: always
    links:
      - mongo
      - elasticsearch
  mongo:
    image: mongo:4.2
    ports:
      - "9000:27017"
    container_name: vstay-db
    restart: always
    volumes:
      - "./data/mongo:/data/db"
    environment:
      - DB_HOST=mongo
      - DB_PORT=27017
    command: mongod
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.3
    container_name: vstay_elasticsearch
    environment:
      - node.name=elasticsearch
      - cluster.name=datasearch
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - cluster.initial_master_nodes=elasticsearch
    ports:
      - 9200:9200
      - 9300:9300
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - ./data/elastic:/usr/share/elasticsearch/data
  kibana:
    image: docker.elastic.co/kibana/kibana:7.9.3
    container_name: vstay_kibana
    logging:
      driver: none

elastic.js

const { Client } = require("@elastic/elasticsearch");

module.exports.connectES = () => {
  try {
    const client = new Client({
      node: "http://localhost:9200",
      maxRetries: 5,
      requestTimeout: 60000,
      sniffOnStart: true,
    });

    client.ping(
      {
        // ping usually has a 3000ms timeout
        requestTimeout: Infinity,
        // undocumented params are appended to the query string
        hello: "elasticsearch!",
      },
      function (error) {
        if (error) {
          console.log(error);
          console.trace("elasticsearch cluster is down!");
        } else {
          console.log("All is well");
        }
      }
    );

    return client;
  } catch (error) {
    console.log(error);
    process.exit(0);
  }
};

index.js 进行连接:

const { app } = require("./config/express");

const { connect: dbConnect } = require("./config/mongo");

const { connectES } = require("./config/elastic");

const { port, domain, env } = require("./config/vars");

let appInstance;
const startApp = async () => {
  const dbConnection = await dbConnect();
  const ESConnection = await connectES();

  app.locals.db = dbConnection;
  app.locals.ESClient = ESConnection;

  app.listen(port, () =>
    console.log(`Server is listening on ${domain.API} (${env})`)
  );

  return app;
};

appInstance = startApp();

module.exports = { appInstance };

错误

我有一个被docker化的应用程序(NodeJS和Elasticsearch-v7.9.3)。服务器可以很好地启动,但是当我尝试在Elasticsearch中创建 Client 实例时,它显示了一个错误:

ConnectionError: connect ECONNREFUSED 127.0.0.1:9200
                            at ClientRequest.<anonymous> (/app/node_modules/@elastic/elasticsearch/lib/Connection.js:109:18)
                            at ClientRequest.emit (events.js:210:5)
                            at Socket.socketErrorListener (_http_client.js:406:9)
                            at Socket.emit (events.js:210:5)
                            at emitErrorNT (internal/streams/destroy.js:92:8)
                            at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
                            at processTicksAndRejections (internal/process/task_queues.js:80:21) {
                            name: 'ConnectionError',
                            meta: {
                            body: null,
                            statusCode: null,
                            headers: null,
                            meta: {
                              context: null,
                              request: [Object],
                              name: 'elasticsearch-js',
                              connection: [Object],
                              attempts: 5,
                              aborted: false
                            }
                          }
                         }

Elasticsearch和Kibana的服务器已启动,我可以在浏览器上将其连接到:http:// localhost:9200和http:// localhost:5601。

但是当我从nodeJS应用程序连接时,它仍然显示错误。我还试图找到我的容器IP并将其替换为“ localhost”,但仍然无法正常工作。

有人可以帮我解决这个问题吗?谢谢。

我的环境

  • 节点版本:v10.19.0
  • @elastic/elasticsearch 版本:7.9.3
  • os :Linux
  • 环境:Docker

1 个答案:

答案 0 :(得分:1)

运行docker-compose文件时,弹性搜索服务实例将不可用于localhost上的后端服务。在您的node.js代码中将http://localhost:9200更改为http://elasticsearch:9200

docker compose自动为每个服务创建与服务名称相同的dns条目。