You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将NestJS容器连接到Elasticsearch容器?

容器化NestJS对接Docker Compose部署的Elasticsearch(用户名密码认证)配置方案

目前针对容器化NestJS通过HTTP协议对接带用户名密码认证的Docker Compose部署Elasticsearch的场景,公开文档较少,不少开发者都遇到配置障碍。以下是我验证通过的完整配置方案:

1. Docker Compose部署Elasticsearch服务

首先编写docker-compose.yml,配置带基础认证的Elasticsearch容器,同时确保网络互通:

version: '3.8'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.11.3
    container_name: es-container
    environment:
      - discovery.type=single-node
      - ES_JAVA_OPTS=-Xms512m -Xmx512m
      - xpack.security.enabled=true
      - ELASTIC_USERNAME=elastic  # 设置ES用户名
      - ELASTIC_PASSWORD=your_strong_password  # 设置ES密码,生产环境请使用强密码
    ports:
      - "9200:9200"
      - "9300:9300"
    volumes:
      - es-data:/usr/share/elasticsearch/data
    networks:
      - app-network

volumes:
  es-data:
    driver: local

networks:
  app-network:
    driver: bridge

启动命令:

docker-compose up -d

2. 容器化NestJS项目配置

2.1 安装依赖

在NestJS项目中安装Elasticsearch客户端依赖:

npm install @nestjs/elasticsearch @elastic/elasticsearch

2.2 配置Elasticsearch模块

在app.module.ts中配置ElasticsearchModule,注意容器间调用需使用服务名elasticsearch而非localhost,同时传入认证信息:

import { Module } from '@nestjs/common';
import { ElasticsearchModule } from '@nestjs/elasticsearch';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    ElasticsearchModule.register({
      node: 'http://elasticsearch:9200', // 使用Docker Compose中的ES服务名
      auth: {
        username: 'elastic',
        password: 'your_strong_password', // 与ES配置的密码保持一致
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

2.3 编写测试服务示例

创建简单服务验证ES连接,比如在app.service.ts中添加索引创建和数据插入方法:

import { Injectable } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';

@Injectable()
export class AppService {
  constructor(private readonly elasticsearchService: ElasticsearchService) {}

  // 创建索引
  async createIndex(indexName: string) {
    const exists = await this.elasticsearchService.indices.exists({ index: indexName });
    if (!exists) {
      await this.elasticsearchService.indices.create({ index: indexName });
    }
    return `Index ${indexName} created or already exists`;
  }

  // 插入测试文档
  async insertDocument(indexName: string, document: any) {
    const result = await this.elasticsearchService.index({
      index: indexName,
      document,
    });
    return result;
  }
}

2.4 容器化NestJS项目

编写Dockerfile将NestJS打包为容器:

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .
RUN npm run build

EXPOSE 3000

CMD ["node", "dist/main"]

修改docker-compose.yml,将NestJS服务加入同一网络:

# 在原docker-compose.yml中添加NestJS服务
services:
  # ... 原有elasticsearch服务 ...
  nestjs-app:
    build: .
    container_name: nestjs-container
    ports:
      - "3000:3000"
    depends_on:
      - elasticsearch
    networks:
      - app-network

3. 验证配置

启动所有服务后,通过NestJS接口调用测试ES连接(比如调用createIndex方法),若返回成功则说明配置生效。

内容的提问来源于stack exchange,提问作者Valentin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:18:20