关于这种情况的文档并不多,而且很多人都面临着这个问题,所以这是我的工作设置,使用:
这是代码
搜索.module.ts
import { Module } from "@nestjs/common";
import { ElasticsearchModule } from "@nestjs/elasticsearch";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { SearchService } from "./service/search.service";
@Module({
imports: [
ConfigModule,
ElasticsearchModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
node: configService.get("ELASTICSEARCH_NODE"),
auth: {
username: "elastic",
password: configService.get("ELASTICSEARCH_PASSWORD") ?? "",
},
}),
inject: [ConfigService],
}),
],
exports: [SearchService],
providers: [SearchService],
})
export class SearchModule {}
搜索.service.ts
import { Injectable } from "@nestjs/common";
import { ElasticsearchService } from "@nestjs/elasticsearch";
@Injectable()
export class SearchService {
public client: ElasticsearchService;
constructor(elasticsearchService: ElasticsearchService) {
this.client = elasticsearchService;
}
}
docker-compose.yml
services:
elasticsearch:
image: elasticsearch:8.17.0
container_name: elasticsearch
restart: "no"
ports:
- "127.0.0.1:9200:9200"
env_file:
- elasticsearch_var.env
environment:
- node.name=elasticsearch
- ES_JAVA_OPTS=-Xms512m -Xmx512m
- discovery.type=single-node
- bootstrap.memory_lock=true
ulimits:
memlock:
soft: -1
hard: -1
volumes:
- elasticsearch_volumes:/usr/share/elasticsearch/data
networks:
- db_networks
networks:
db_networks:
driver: bridge
elasticsearch_var.env
ELASTIC_PASSWORD=yourpassword
.env
ELASTICSEARCH_NODE="http://elasticsearch:9200"
ELASTICSEARCH_PASSWORD=yourpassword
确保将您的 NestJS 容器连接到 Elastic 使用的同一网络,一切都会正常工作,这样您就可以从应用程序中的任何位置高效地调用您的搜索服务(当您向其提供搜索模块和服务时)。
如果您想启用 https,则无需做太多事情,您可以通过启用 Elasticsearch 的 xpass 安全性来在 compose 中启用它。
请注意您在撰写中的端口设置以及为elasticsearch节点指定的名称,如果您仍然遇到任何问题,我很乐意回答更多帮助
祝大家好运