使用 Docker Compose 搭建 Elasticsearch 集群
Haiya Lv3

资源准备

服务器 3 台,安装 Docker & Compose。拉取 Elasticsearch 镜像。

1
docker pull elasticsearch:8.16.0

本文中使用的三台服务器 IP 分别为:

  • 10.1.1.2
  • 10.1.1.3
  • 10.1.1.4

docker-compose.yml

分别在三台服务器上创建 docker-compose.yml 文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
services:
es:
image: elasticsearch:8.16.0
container_name: es
environment:
- node.name=${node_name}
- cluster.name=${cluster_name}
- discovery.seed_hosts=${seed_hosts}
- cluster.initial_master_nodes=${initial_master_nodes}
- network.publish_host=${publish_host}
- bootstrap.memory_lock=true
- xpack.security.enabled=false
# - "ES_JAVA_OPTS=-Xms32g -Xmx32g"
volumes:
- es_data:/usr/share/elasticsearch/data
ulimits:
memlock:
soft: -1
hard: -1
ports:
- 9200:9200
- 9300:9300
volumes:
es_data:

该配置文件中:

  • 为了避免数据丢失,将 Elasticsearch 数据目录挂载到 es_data 卷中。
  • ES_JAVA_OPTS 配置 JVM 内存,可根据实际情况调整。

.env

分别在三台服务器的 docker-compose.yml 同级目录下创建 .env 文件。

以主机 10.1.1.2 为例,内容如下:

1
2
3
4
5
node_name=es01
cluster_name=es-docker-cluster
seed_hosts=10.1.1.2,10.1.1.3,10.1.1.4
initial_master_nodes=10.1.1.2,10.1.1.3,10.1.1.4
publish_host=10.1.1.2

各项配置说明如下:

  • node_name: 节点名称,每台服务器上使用不同的名称
  • cluster_name: 集群名称,每台服务器上使用相同的名称
  • seed_hosts: 集群自动发现所需的初始主机节点列表,每台服务器上配置相同,使用逗号分隔
  • initial_master_nodes: 指定集群的初始主节点列表,每台服务器上配置相同,使用逗号分隔
  • publish_host: 发布地址,修改为当前服务器 IP

通常情况下,每台主机的 node_namepublish_host 配置不同,其他配置相同。

启动集群

三台服务器均需要执行以下命令:

1
docker compose up -d

使用以下命令查看日志:

1
docker compose logs -f

耐心等待,确定没有报错信息后,进行下一步。

验证

在任意一台服务器上执行以下命令,查看集群状态:

1
curl -X GET "localhost:9200/_cat/nodes?v&pretty"

输出结果如下:

1
2
3
4
ip       heap.percent ram.percent cpu load_1m load_5m load_15m node.role   master name
10.1.1.2 13 97 0 0.00 0.00 0.00 cdfhilmrstw - es01
10.1.1.3 14 98 0 0.00 0.00 0.00 cdfhilmrstw - es03
10.1.1.4 6 98 0 0.00 0.00 0.00 cdfhilmrstw * es02
由 Hexo 驱动 & 主题 Keep