目录
- 1. 简介
- 2. 环境要求
- 3. 安装前准备
- 4. 安装 Elasticsearch
- 5. 配置 Elasticsearch
- 6. 启动与管理服务
- 7. 验证安装
- 8. 基本使用
- 9. 安全配置
- 10. 性能优化
- 11. 常见问题与解决方案
- 12. 备份与恢复
1. 简介
Elasticsearch 是一个基于 Apache Lucene 的开源分布式搜索和分析引擎,适用于所有类型的数据,包括文本、数字、地理空间、结构化和非结构化数据。
主要特性
- 分布式架构:自动分片和副本管理
- RESTful API:通过 HTTP 进行交互
- 近实时搜索:索引后几乎立即可搜索
- 全文检索:强大的文本搜索和分析能力
- 高可用性:支持集群和自动故障转移
2. 环境要求
2.1 硬件要求
| 组件 | 最低配置 | 推荐配置 |
|---|---|---|
| CPU | 2核 | 4核以上 |
| 内存 | 4GB | 16GB以上 |
| 磁盘 | 10GB | 100GB以上 SSD |
| 网络 | 100Mbps | 1Gbps |
💡 资源受限环境说明
如果您的服务器配置为 2核2G,Elasticsearch 仍然可以运行,但需要进行以下调整:
- JVM 堆内存:设置为 512MB-1GB(不超过物理内存的50%)
- 索引分片数:减少分片数量,单节点环境建议设置为1
- 索引副本数:设置为0(单节点无需副本)
- 刷新间隔:增加到30s或更长,减少资源消耗
- 数据量限制:建议数据量不超过10GB
- 并发请求:限制并发查询数,避免OOM
# 2核2G 环境推荐的 JVM 配置
-Xms512m
-Xmx1g2.2 软件要求
- 操作系统:CentOS 7/8、Ubuntu 18.04/20.04/22.04、RHEL 7/8
- Java:JDK 11 或更高版本(Elasticsearch 8.x 自带 OpenJDK)
- 依赖包:glibc 2.17 或更高版本
2.3 系统参数要求
- 最大文件描述符:至少 65535
- 最大线程数:至少 4096
- 虚拟内存:至少 262144
3. 安装前准备
3.1 创建 Elasticsearch 用户
# 创建 elasticsearch 用户组和用户
sudo groupadd elasticsearch
sudo useradd -g elasticsearch -s /bin/bash -m elasticsearch
# 设置密码(可选)
sudo passwd elasticsearch3.2 配置系统参数
3.2.1 修改文件描述符限制
# 编辑 limits.conf
sudo vim /etc/security/limits.conf
# 添加以下内容
elasticsearch soft nofile 65535
elasticsearch hard nofile 65535
elasticsearch soft nproc 4096
elasticsearch hard nproc 40963.2.2 修改虚拟内存
# 编辑 sysctl.conf
sudo vim /etc/sysctl.conf
# 添加以下内容
vm.max_map_count=262144
# 使配置生效
sudo sysctl -p3.2.3 禁用 Swap(推荐)
# 临时禁用
sudo swapoff -a
# 永久禁用,编辑 /etc/fstab,注释掉 swap 行
sudo vim /etc/fstab
# 注释掉类似这样的行:
# /dev/mapper/centos-swap swap swap defaults 0 03.3 安装 Java(如果需要)
# CentOS/RHEL
sudo yum install java-11-openjdk java-11-openjdk-devel -y
# Ubuntu/Debian
sudo apt update
sudo apt install openjdk-11-jdk -y
# 验证 Java 安装
java -version4. 安装 Elasticsearch
4.1 方法一:使用 RPM 包安装(CentOS/RHEL)
4.1.1 导入 GPG 密钥
sudo rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch4.1.2 创建 Yum 仓库
选项 A:官方源(国外)
sudo vim /etc/yum.repos.d/elasticsearch.repo添加以下内容:
[elasticsearch]
name=Elasticsearch repository for 8.x packages
baseurl=https://artifacts.elastic.co/packages/8.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md选项 B:清华大学镜像源(国内推荐) 🇨🇳
sudo vim /etc/yum.repos.d/elasticsearch.repo添加以下内容:
[elasticsearch]
name=Elasticsearch repository for 8.x packages
baseurl=https://mirrors.tuna.tsinghua.edu.cn/elasticstack/yum/elastic-8.x/
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md选项 C:阿里云镜像源(国内备用) 🇨🇳
sudo vim /etc/yum.repos.d/elasticsearch.repo添加以下内容:
[elasticsearch]
name=Elasticsearch repository for 8.x packages
baseurl=https://mirrors.aliyun.com/elasticstack/yum/elastic-8.x/
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md4.1.3 安装 Elasticsearch
sudo yum install elasticsearch -y4.2 方法二:使用 DEB 包安装(Ubuntu/Debian)
4.2.1 导入 GPG 密钥
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-keyring.gpg4.2.2 安装 apt-transport-https
sudo apt-get install apt-transport-https -y4.2.3 添加 APT 仓库
选项 A:官方源(国外)
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list选项 B:清华大学镜像源(国内推荐) 🇨🇳
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://mirrors.tuna.tsinghua.edu.cn/elasticstack/apt/8.x stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list选项 C:阿里云镜像源(国内备用) 🇨🇳
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://mirrors.aliyun.com/elasticstack/apt/8.x stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list4.2.4 安装 Elasticsearch
sudo apt-get update
sudo apt-get install elasticsearch -y4.3 方法三:使用 tar.gz 包安装(通用)
4.3.1 下载 Elasticsearch
选项 A:官方源(国外)
# 切换到 elasticsearch 用户
su - elasticsearch
# 下载最新版本(以 8.11.0 为例)
cd /opt
sudo wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-8.11.0-linux-x86_64.tar.gz
# 解压
sudo tar -xzf elasticsearch-8.11.0-linux-x86_64.tar.gz
# 重命名(可选)
sudo mv elasticsearch-8.11.0 elasticsearch
# 修改所有者
sudo chown -R elasticsearch:elasticsearch /opt/elasticsearch选项 B:清华大学镜像源(国内推荐) 🇨🇳
# 下载最新版本(以 8.11.0 为例)
cd /opt
sudo wget https://mirrors.tuna.tsinghua.edu.cn/elasticstack/downloads/elasticsearch/elasticsearch-8.11.0-linux-x86_64.tar.gz
# 解压
sudo tar -xzf elasticsearch-8.11.0-linux-x86_64.tar.gz
# 重命名(可选)
sudo mv elasticsearch-8.11.0 elasticsearch
# 修改所有者
sudo chown -R elasticsearch:elasticsearch /opt/elasticsearch选项 C:华为云镜像源(国内备用) 🇨🇳
# 下载最新版本
cd /opt
sudo wget https://mirrors.huaweicloud.com/elasticsearch/8.11.0/elasticsearch-8.11.0-linux-x86_64.tar.gz
# 解压和配置同上
sudo tar -xzf elasticsearch-8.11.0-linux-x86_64.tar.gz
sudo mv elasticsearch-8.11.0 elasticsearch
sudo chown -R elasticsearch:elasticsearch /opt/elasticsearch💡 下载速度慢的解决方案
如果下载速度很慢,可以使用迅雷等下载工具下载后上传到服务器:
# 在本地Windows下载后,使用scp上传
scp elasticsearch-8.11.0-linux-x86_64.tar.gz root@你的服务器IP:/opt/4.4 重要:保存初始密码和令牌
安装完成后,系统会自动生成以下信息,请务必保存:
✅ Elasticsearch security features have been automatically configured!
✅ Authentication is enabled and cluster connections are encrypted.
ℹ️ Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
lhQpLELkjkrawaBoaz0Q
ℹ️ HTTP CA certificate SHA-256 fingerprint:
a52dd93511e8c6645e2c2e2e03aa98a2b3e4dc81c71c5e82c99f8efff3526f6c
ℹ️ Configure Kibana to use this cluster:
• Run Kibana and click the configuration link in the terminal when Kibana starts.
• Copy the following enrollment token and paste it into Kibana in your browser:
eyJ2ZXIiOiI4LjExLjAiLC...
安装日志
Selecting previously unselected package elasticsearch.
(Reading database ... 104136 files and directories currently installed.)
Preparing to unpack .../elasticsearch_8.19.6_amd64.deb ...
Unpacking elasticsearch (8.19.6) ...
Setting up elasticsearch (8.19.6) ...
--------------------------- Security autoconfiguration information ------------------------------
Authentication and authorization are enabled.
TLS for the transport and HTTP layers is enabled and configured.
The generated password for the elastic built-in superuser is : d8Yoo5g5g*TFbcAFpJSg
If this node should join an existing cluster, you can reconfigure this with
'/usr/share/elasticsearch/bin/elasticsearch-reconfigure-node --enrollment-token <token-here>'
after creating an enrollment token on your existing cluster.
You can complete the following actions at any time:
Reset the password of the elastic built-in superuser with
'/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic'.
Generate an enrollment token for Kibana instances with
'/usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana'.
Generate an enrollment token for Elasticsearch nodes with
'/usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s node'.
-------------------------------------------------------------------------------------------------
### NOT starting on installation, please execute the following statements to configure elasticsearch service to start automatically using systemd
sudo systemctl daemon-reload
sudo systemctl enable elasticsearch.service
### You can start elasticsearch service by executing
sudo systemctl start elasticsearch.service✅ Elasticsearch 8.19.6 安装日志分析
(完成配置后使用这里只是分析!!!)
📊 安装概况
- 版本:Elasticsearch 8.19.6 (amd64)
- 安装方式:DEB 包安装
- 安装状态:✅ 成功完成
- 当前状态:⚠️ 未启动(需要手动启动)
🔐 重要安全信息
🔑 超级管理员密码(务必保存!)
用户名:elastic
密码:d8Yoo5g5g*TFbcAFpJSg⚠️ 警告:这是系统自动生成的密码,只显示一次,必须立即保存!
🛡️ 安全特性(已自动配置)
- ✅ 认证和授权:已启用
- ✅ TLS 加密:传输层和 HTTP 层都已启用
- ✅ 证书:已自动生成和配置
🚀 下一步操作
1️⃣ 启动服务(必须执行)
# 重新加载 systemd 配置
sudo systemctl daemon-reload
# 设置开机自启动
sudo systemctl enable elasticsearch.service
# 启动 Elasticsearch 服务
sudo systemctl start elasticsearch.service
# 查看服务状态
sudo systemctl status elasticsearch.service2️⃣ 验证安装(等待 15-30 秒后执行)
# 使用自动生成的密码测试连接
curl -k -u elastic:d8Yoo5g5g*TFbcAFpJSg https://localhost:9200
# 查看集群健康状态
curl -k -u elastic:d8Yoo5g5g*TFbcAFpJSg https://localhost:9200/_cluster/health?pretty3️⃣ 查看日志(如果启动失败)
# 查看实时日志
sudo journalctl -u elasticsearch -f
# 查看最近 50 条日志
sudo journalctl -u elasticsearch -n 50🛠️ 可用的管理命令
重置 elastic 用户密码
sudo /usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic生成 Kibana 连接令牌(如需安装 Kibana)
sudo /usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana生成新节点加入令牌(如需搭建集群)
sudo /usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s node重新配置节点(加入现有集群)
sudo /usr/share/elasticsearch/bin/elasticsearch-reconfigure-node --enrollment-token <令牌>📁 重要文件路径
| 类型 | 路径 |
|---|---|
| 配置文件 | /etc/elasticsearch/elasticsearch.yml |
| 数据目录 | /var/lib/elasticsearch |
| 日志目录 | /var/log/elasticsearch |
| 证书目录 | /etc/elasticsearch/certs |
| 主程序目录 | /usr/share/elasticsearch |
| 可执行文件 | /usr/share/elasticsearch/bin/ |
⚠️ 注意事项
- 密码保存:
d8Yoo5g5g*TFbcAFpJSg必须立即保存到安全的地方 - 服务未启动:安装后不会自动启动,需要手动执行启动命令
- HTTPS 访问:由于启用了 TLS,访问时需要使用
https://而不是http:// - 证书验证:测试时可以使用
-k参数跳过证书验证,生产环境建议使用正确的证书 - 防火墙:确保防火墙允许 9200 和 9300 端口
🎯 快速启动检查清单
- [ ] 保存 elastic 用户密码:
d8Yoo5g5g*TFbcAFpJSg - [ ] 执行
sudo systemctl daemon-reload - [ ] 执行
sudo systemctl enable elasticsearch.service - [ ] 执行
sudo systemctl start elasticsearch.service - [ ] 等待 15-30 秒
- [ ] 测试连接:
curl -k -u elastic:d8Yoo5g5g*TFbcAFpJSg https://localhost:9200 - [ ] 检查集群健康状态
现在可以执行启动命令了! 🚀
5. 配置 Elasticsearch
5.1 主配置文件位置
- RPM/DEB 安装:
/etc/elasticsearch/elasticsearch.yml - tar.gz 安装:
/opt/elasticsearch/config/elasticsearch.yml
5.2 基本配置
sudo vim /etc/elasticsearch/elasticsearch.yml5.2.1 集群和节点配置
# 集群名称
cluster.name: my-elasticsearch-cluster
# 节点名称
node.name: node-1
# 节点角色(可选配置)
node.roles: [ master, data, ingest ]
# 数据和日志路径
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch💡 2核2G 环境额外配置建议
# 限制线程池大小(降低资源消耗)
thread_pool.write.queue_size: 200
thread_pool.search.queue_size: 500
# 降低缓存大小
indices.queries.cache.size: 5%
indices.requests.cache.size: 1%
# 限制字段数据缓存
indices.fielddata.cache.size: 15%5.2.2 网络配置
# 绑定的网络地址
# 0.0.0.0 表示所有网络接口,生产环境建议指定具体 IP
network.host: 0.0.0.0
# HTTP 端口
http.port: 9200
# TCP 传输端口
transport.port: 93005.2.3 发现和集群配置
# 单节点模式(开发环境)
discovery.type: single-node
# 集群模式(生产环境)
# discovery.seed_hosts: ["192.168.1.101", "192.168.1.102", "192.168.1.103"]
# cluster.initial_master_nodes: ["node-1", "node-2", "node-3"]5.2.4 内存配置
编辑 JVM 配置文件:
sudo vim /etc/elasticsearch/jvm.options或对于 tar.gz 安装:
vim /opt/elasticsearch/config/jvm.options配置堆内存(建议设置为物理内存的 50%,但不超过 32GB):
# 示例:8GB 物理内存
-Xms4g
-Xmx4g
# 示例:2GB 物理内存(资源受限环境)
-Xms512m
-Xmx1g5.3 目录权限设置
# RPM/DEB 安装
sudo chown -R elasticsearch:elasticsearch /var/lib/elasticsearch
sudo chown -R elasticsearch:elasticsearch /var/log/elasticsearch
sudo chown -R elasticsearch:elasticsearch /etc/elasticsearch
# tar.gz 安装
sudo chown -R elasticsearch:elasticsearch /opt/elasticsearch5.4 2核2G 环境完整配置示例
如果您的服务器是 2核2G 配置,这里提供一个完整的优化配置方案:
5.4.1 elasticsearch.yml 配置
# 集群配置
cluster.name: my-es-cluster
node.name: node-1
discovery.type: single-node
# 网络配置
network.host: 0.0.0.0
http.port: 9200
# 路径配置
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
# 性能优化(2核2G 专用)
indices.queries.cache.size: 5%
indices.requests.cache.size: 1%
indices.fielddata.cache.size: 15%
thread_pool.write.queue_size: 200
thread_pool.search.queue_size: 500
# 安全配置(可选:关闭以节省资源)
xpack.security.enabled: false
xpack.security.http.ssl.enabled: false
xpack.security.transport.ssl.enabled: false5.4.2 jvm.options 配置
# 堆内存设置(2GB 物理内存)
-Xms512m
-Xmx1g
# GC 配置
-XX:+UseG1GC
-XX:G1ReservePercent=25
# 其他优化
-XX:+AlwaysPreTouch
-Xss1m
-Djava.awt.headless=true5.4.3 创建索引时的建议设置
curl -k -X PUT "https://localhost:9200/your_index" \
-H 'Content-Type: application/json' \
-d '{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0,
"refresh_interval": "30s",
"translog.durability": "async",
"translog.sync_interval": "30s"
}
}'6. 启动与管理服务
6.1 使用 Systemd 管理(RPM/DEB 安装)
6.1.1 启动服务
# 启动 Elasticsearch
sudo systemctl start elasticsearch
# 设置开机自启动
sudo systemctl enable elasticsearch
# 查看服务状态
sudo systemctl status elasticsearch6.1.2 停止和重启服务
# 停止服务
sudo systemctl stop elasticsearch
# 重启服务
sudo systemctl restart elasticsearch
# 重新加载配置
sudo systemctl daemon-reload6.1.3 查看日志
# 查看实时日志
sudo journalctl -u elasticsearch -f
# 查看最近的日志
sudo journalctl -u elasticsearch -n 100
# 查看日志文件
sudo tail -f /var/log/elasticsearch/my-elasticsearch-cluster.log6.2 手动启动(tar.gz 安装)
# 切换到 elasticsearch 用户
su - elasticsearch
# 后台启动
/opt/elasticsearch/bin/elasticsearch -d -p pid
# 停止(使用保存的 pid)
kill `cat /opt/elasticsearch/pid`
# 查看日志
tail -f /opt/elasticsearch/logs/my-elasticsearch-cluster.log7. 验证安装
7.1 检查服务状态
# 等待服务启动(通常需要 10-30 秒)
sleep 15
# 使用 curl 检查(需要身份验证)
curl --cacert /etc/elasticsearch/certs/http_ca.crt -u elastic:你的密码 https://localhost:9200
# 或者禁用 SSL 验证(仅测试用)
curl -k -u elastic:你的密码 https://localhost:92007.2 预期输出
{
"name" : "node-1",
"cluster_name" : "my-elasticsearch-cluster",
"cluster_uuid" : "xxxxxxxxxxxxxxxxxxx",
"version" : {
"number" : "8.11.0",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "xxxxxxx",
"build_date" : "2023-11-04T10:04:57.184859352Z",
"build_snapshot" : false,
"lucene_version" : "9.8.0",
"minimum_wire_compatibility_version" : "7.17.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "You Know, for Search"
}7.3 查看集群健康状态
curl -k -u elastic:你的密码 https://localhost:9200/_cluster/health?pretty健康状态说明:
- green:所有主分片和副本分片都可用
- yellow:所有主分片可用,但部分副本分片不可用
- red:部分主分片不可用
8. 基本使用
8.1 索引操作
8.1.1 创建索引
# 创建一个名为 "products" 的索引
curl -k -X PUT "https://localhost:9200/products" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
},
"mappings": {
"properties": {
"name": { "type": "text" },
"price": { "type": "float" },
"description": { "type": "text" },
"created_at": { "type": "date" }
}
}
}'8.1.2 查看索引
# 查看所有索引
curl -k -u elastic:你的密码 "https://localhost:9200/_cat/indices?v"
# 查看特定索引信息
curl -k -u elastic:你的密码 "https://localhost:9200/products?pretty"8.1.3 删除索引
curl -k -X DELETE "https://localhost:9200/products" \
-u elastic:你的密码8.2 文档操作
8.2.1 添加文档
# 自动生成 ID
curl -k -X POST "https://localhost:9200/products/_doc" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"name": "笔记本电脑",
"price": 5999.00,
"description": "高性能办公笔记本",
"created_at": "2025-11-03"
}'
# 指定 ID
curl -k -X PUT "https://localhost:9200/products/_doc/1" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"name": "台式电脑",
"price": 8999.00,
"description": "高性能游戏台式机",
"created_at": "2025-11-03"
}'8.2.2 批量添加文档
curl -k -X POST "https://localhost:9200/_bulk" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
--data-binary @- << EOF
{"index":{"_index":"products","_id":"2"}}
{"name":"鼠标","price":99.00,"description":"无线办公鼠标","created_at":"2025-11-03"}
{"index":{"_index":"products","_id":"3"}}
{"name":"键盘","price":299.00,"description":"机械键盘","created_at":"2025-11-03"}
EOF8.2.3 查询文档
# 根据 ID 查询
curl -k -X GET "https://localhost:9200/products/_doc/1?pretty" \
-u elastic:你的密码
# 查询所有文档
curl -k -X GET "https://localhost:9200/products/_search?pretty" \
-u elastic:你的密码8.2.4 更新文档
# 部分更新
curl -k -X POST "https://localhost:9200/products/_update/1" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"doc": {
"price": 7999.00
}
}'
# 完整替换
curl -k -X PUT "https://localhost:9200/products/_doc/1" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"name": "台式电脑",
"price": 7999.00,
"description": "高性能游戏台式机(升级版)",
"created_at": "2025-11-03"
}'8.2.5 删除文档
curl -k -X DELETE "https://localhost:9200/products/_doc/1" \
-u elastic:你的密码8.3 搜索查询
8.3.1 全文搜索
curl -k -X GET "https://localhost:9200/products/_search?pretty" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"query": {
"match": {
"name": "电脑"
}
}
}'8.3.2 精确匹配
curl -k -X GET "https://localhost:9200/products/_search?pretty" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"query": {
"term": {
"price": 5999.00
}
}
}'8.3.3 范围查询
curl -k -X GET "https://localhost:9200/products/_search?pretty" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"query": {
"range": {
"price": {
"gte": 100,
"lte": 1000
}
}
}
}'8.3.4 组合查询
curl -k -X GET "https://localhost:9200/products/_search?pretty" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"query": {
"bool": {
"must": [
{ "match": { "description": "办公" }}
],
"filter": [
{ "range": { "price": { "lte": 6000 }}}
]
}
}
}'8.3.5 聚合查询
# 统计平均价格
curl -k -X GET "https://localhost:9200/products/_search?pretty" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"size": 0,
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}'9. 安全配置
9.1 重置用户密码
# 重置 elastic 用户密码
cd /usr/share/elasticsearch/bin # RPM/DEB 安装
# 或
cd /opt/elasticsearch/bin # tar.gz 安装
# 交互式重置
sudo ./elasticsearch-reset-password -u elastic
# 自动生成密码
sudo ./elasticsearch-reset-password -u elastic -a
# 手动设置密码
sudo ./elasticsearch-reset-password -u elastic -i9.2 创建新用户
# 使用 API 创建用户
curl -k -X POST "https://localhost:9200/_security/user/myuser" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"password" : "mypassword",
"roles" : [ "kibana_admin", "monitoring_user"],
"full_name" : "My User",
"email" : "myuser@example.com"
}'9.3 配置 SSL/TLS
Elasticsearch 8.x 默认启用 TLS。如果需要禁用(仅开发环境):
# 编辑 elasticsearch.yml
xpack.security.enabled: true
xpack.security.http.ssl.enabled: false
xpack.security.transport.ssl.enabled: false9.4 配置防火墙
# CentOS/RHEL
sudo firewall-cmd --permanent --add-port=9200/tcp
sudo firewall-cmd --permanent --add-port=9300/tcp
sudo firewall-cmd --reload
# Ubuntu/Debian
sudo ufw allow 9200/tcp
sudo ufw allow 9300/tcp
sudo ufw reload10. 性能优化
10.1 JVM 参数优化
# 编辑 jvm.options
sudo vim /etc/elasticsearch/jvm.options添加以下配置:
# GC 配置
-XX:+UseG1GC
-XX:G1ReservePercent=25
-XX:InitiatingHeapOccupancyPercent=30
# 堆转储配置(OOM 时)
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/var/lib/elasticsearch
# GC 日志
-Xlog:gc*,gc+age=trace,safepoint:file=/var/log/elasticsearch/gc.log:utctime,pid,tags:filecount=32,filesize=64m10.2 索引优化
# 调整刷新间隔
curl -k -X PUT "https://localhost:9200/products/_settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"index": {
"refresh_interval": "30s"
}
}'
# 增加批量处理大小
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"persistent": {
"http.max_content_length": "500mb"
}
}'10.3 磁盘优化
# 在 elasticsearch.yml 中配置
index.merge.scheduler.max_thread_count: 1
# 使用 SSD 时
index.store.type: niofs10.4 查询缓存
# 在 elasticsearch.yml 中配置
indices.queries.cache.size: 10%
indices.requests.cache.size: 2%11. 常见问题与解决方案
11.1 服务启动失败
问题:max virtual memory areas vm.max_map_count is too low
解决方案:
sudo sysctl -w vm.max_map_count=262144
echo "vm.max_map_count=262144" | sudo tee -a /etc/sysctl.conf问题:max file descriptors too low
解决方案:
# 编辑 limits.conf
sudo vim /etc/security/limits.conf
# 添加
elasticsearch soft nofile 65535
elasticsearch hard nofile 65535
# 重新登录 elasticsearch 用户11.2 内存不足
问题:OutOfMemoryError
解决方案:
# 1. 增加堆内存(不超过 32GB)
sudo vim /etc/elasticsearch/jvm.options
-Xms8g
-Xmx8g
# 2. 减少内存使用
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"persistent": {
"indices.breaker.total.limit": "70%"
}
}'
# 3. 重启服务
sudo systemctl restart elasticsearch11.3 磁盘空间不足
问题:Disk watermark exceeded
解决方案:
# 1. 清理不需要的索引
curl -k -X DELETE "https://localhost:9200/old_index_*" \
-u elastic:你的密码
# 2. 调整水位线(临时)
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"transient": {
"cluster.routing.allocation.disk.watermark.low": "90%",
"cluster.routing.allocation.disk.watermark.high": "95%",
"cluster.routing.allocation.disk.watermark.flood_stage": "97%"
}
}'
# 3. 释放磁盘空间
sudo du -sh /var/lib/elasticsearch/*11.4 集群状态为 Yellow
问题:副本分片未分配
解决方案:
# 单节点模式:设置副本数为 0
curl -k -X PUT "https://localhost:9200/_settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"index": {
"number_of_replicas": 0
}
}'11.5 无法连接到 Elasticsearch
问题:Connection refused
解决方案:
# 1. 检查服务状态
sudo systemctl status elasticsearch
# 2. 检查端口监听
sudo netstat -tlnp | grep 9200
# 3. 检查防火墙
sudo firewall-cmd --list-all
# 4. 检查日志
sudo tail -f /var/log/elasticsearch/*.log
# 5. 检查网络配置
grep "network.host" /etc/elasticsearch/elasticsearch.yml11.6 认证失败
问题:Authentication failed
解决方案:
# 重置密码
cd /usr/share/elasticsearch/bin
sudo ./elasticsearch-reset-password -u elastic -i
# 或者禁用安全功能(仅开发环境)
echo "xpack.security.enabled: false" | sudo tee -a /etc/elasticsearch/elasticsearch.yml
sudo systemctl restart elasticsearch11.7 2核2G 环境特有问题
问题:频繁 OutOfMemory 错误
解决方案:
# 1. 降低 JVM 堆内存
sudo vim /etc/elasticsearch/jvm.options
-Xms512m
-Xmx1g
# 2. 限制查询结果大小
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"persistent": {
"search.max_buckets": 10000,
"indices.query.bool.max_clause_count": 1024
}
}'
# 3. 减少并发
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"transient": {
"thread_pool.write.queue_size": 100,
"thread_pool.search.queue_size": 300
}
}'问题:启动缓慢或卡住
解决方案:
# 1. 临时禁用 Swap
sudo swapoff -a
# 2. 减少启动超时
sudo vim /etc/systemd/system/elasticsearch.service.d/override.conf
[Service]
TimeoutStartSec=300
# 3. 简化配置,移除非必要功能
sudo vim /etc/elasticsearch/elasticsearch.yml
# 禁用 ML、监控等功能
xpack.ml.enabled: false
xpack.monitoring.collection.enabled: false问题:查询响应慢
解决方案:
# 1. 增加索引刷新间隔
curl -k -X PUT "https://localhost:9200/your_index/_settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"index": {
"refresh_interval": "60s"
}
}'
# 2. 限制返回字段
curl -k -X GET "https://localhost:9200/your_index/_search" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"query": {...},
"_source": ["field1", "field2"],
"size": 10
}'
# 3. 使用过滤而不是查询(filter 有缓存)
curl -k -X GET "https://localhost:9200/your_index/_search" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"query": {
"bool": {
"filter": [
{"term": {"status": "active"}}
]
}
}
}'💡 2核2G 环境使用建议
- ✅ 适合场景:开发、测试、小规模应用(<10GB数据)
- ✅ 索引配置:1个分片,0个副本
- ✅ 数据量:建议不超过 10GB
- ✅ 并发量:建议不超过 10 QPS
- ⚠️ 不适合:生产环境、大数据量、高并发场景
12. 备份与恢复
12.1 快照仓库配置
12.1.1 创建快照目录
sudo mkdir -p /opt/elasticsearch/backup
sudo chown -R elasticsearch:elasticsearch /opt/elasticsearch/backup12.1.2 配置快照路径
# 编辑 elasticsearch.yml
sudo vim /etc/elasticsearch/elasticsearch.yml
# 添加
path.repo: ["/opt/elasticsearch/backup"]
# 重启服务
sudo systemctl restart elasticsearch12.1.3 注册快照仓库
curl -k -X PUT "https://localhost:9200/_snapshot/my_backup" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"type": "fs",
"settings": {
"location": "/opt/elasticsearch/backup"
}
}'12.2 创建快照
12.2.1 备份所有索引
curl -k -X PUT "https://localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true" \
-u elastic:你的密码12.2.2 备份特定索引
curl -k -X PUT "https://localhost:9200/_snapshot/my_backup/snapshot_2" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"indices": "products,users",
"ignore_unavailable": true,
"include_global_state": false
}'12.2.3 查看快照状态
# 查看所有快照
curl -k -X GET "https://localhost:9200/_snapshot/my_backup/_all?pretty" \
-u elastic:你的密码
# 查看特定快照
curl -k -X GET "https://localhost:9200/_snapshot/my_backup/snapshot_1?pretty" \
-u elastic:你的密码12.3 恢复快照
12.3.1 恢复所有索引
curl -k -X POST "https://localhost:9200/_snapshot/my_backup/snapshot_1/_restore" \
-u elastic:你的密码12.3.2 恢复特定索引
curl -k -X POST "https://localhost:9200/_snapshot/my_backup/snapshot_1/_restore" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"indices": "products",
"ignore_unavailable": true,
"include_global_state": false,
"rename_pattern": "products",
"rename_replacement": "products_restored"
}'12.4 定期备份脚本
创建自动备份脚本:
sudo vim /usr/local/bin/es-backup.sh脚本内容:
#!/bin/bash
# Elasticsearch 配置
ES_HOST="https://localhost:9200"
ES_USER="elastic"
ES_PASS="你的密码"
REPO_NAME="my_backup"
DATE=$(date +%Y%m%d_%H%M%S)
SNAPSHOT_NAME="snapshot_${DATE}"
# 创建快照
echo "开始创建快照: ${SNAPSHOT_NAME}"
curl -k -X PUT "${ES_HOST}/_snapshot/${REPO_NAME}/${SNAPSHOT_NAME}?wait_for_completion=true" \
-u ${ES_USER}:${ES_PASS} \
-H 'Content-Type: application/json' \
-d '{
"ignore_unavailable": true,
"include_global_state": false
}'
# 检查结果
if [ $? -eq 0 ]; then
echo "快照创建成功: ${SNAPSHOT_NAME}"
# 删除 7 天前的快照
OLD_DATE=$(date -d "7 days ago" +%Y%m%d)
echo "清理旧快照..."
curl -k -X DELETE "${ES_HOST}/_snapshot/${REPO_NAME}/snapshot_${OLD_DATE}_*" \
-u ${ES_USER}:${ES_PASS}
else
echo "快照创建失败"
exit 1
fi设置权限并添加到 crontab:
sudo chmod +x /usr/local/bin/es-backup.sh
# 添加定时任务(每天凌晨 2 点执行)
sudo crontab -e
0 2 * * * /usr/local/bin/es-backup.sh >> /var/log/es-backup.log 2>&113. 监控与维护
13.1 集群监控
13.1.1 查看集群状态
# 集群健康
curl -k -u elastic:你的密码 "https://localhost:9200/_cluster/health?pretty"
# 节点信息
curl -k -u elastic:你的密码 "https://localhost:9200/_cat/nodes?v"
# 索引状态
curl -k -u elastic:你的密码 "https://localhost:9200/_cat/indices?v&s=store.size:desc"
# 分片分配
curl -k -u elastic:你的密码 "https://localhost:9200/_cat/shards?v"13.1.2 查看资源使用
# 线程池
curl -k -u elastic:你的密码 "https://localhost:9200/_cat/thread_pool?v"
# 内存使用
curl -k -u elastic:你的密码 "https://localhost:9200/_cat/nodes?v&h=name,heap.percent,ram.percent,cpu"
# JVM 信息
curl -k -u elastic:你的密码 "https://localhost:9200/_nodes/stats/jvm?pretty"13.2 性能指标
# 慢查询日志配置
curl -k -X PUT "https://localhost:9200/products/_settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"index.search.slowlog.threshold.query.warn": "10s",
"index.search.slowlog.threshold.query.info": "5s",
"index.search.slowlog.threshold.fetch.warn": "1s",
"index.indexing.slowlog.threshold.index.warn": "10s"
}'13.3 日常维护任务
13.3.1 清理旧索引
# 删除 30 天前的日志索引
curl -k -X DELETE "https://localhost:9200/logs-2025.09.*" \
-u elastic:你的密码13.3.2 优化索引
# 强制合并索引(减少段数量)
curl -k -X POST "https://localhost:9200/products/_forcemerge?max_num_segments=1" \
-u elastic:你的密码13.3.3 清理缓存
# 清理所有缓存
curl -k -X POST "https://localhost:9200/_cache/clear" \
-u elastic:你的密码14. 升级 Elasticsearch
14.1 升级前准备
# 1. 备份配置文件
sudo cp -r /etc/elasticsearch /etc/elasticsearch.backup
# 2. 创建快照
curl -k -X PUT "https://localhost:9200/_snapshot/my_backup/pre_upgrade_snapshot?wait_for_completion=true" \
-u elastic:你的密码
# 3. 禁用分片分配
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"persistent": {
"cluster.routing.allocation.enable": "primaries"
}
}'
# 4. 停止索引并执行同步刷新
curl -k -X POST "https://localhost:9200/_flush/synced" \
-u elastic:你的密码14.2 执行升级
# CentOS/RHEL
sudo yum update elasticsearch -y
# Ubuntu/Debian
sudo apt-get update
sudo apt-get upgrade elasticsearch -y
# 重启服务
sudo systemctl restart elasticsearch14.3 升级后操作
# 1. 等待节点加入集群
sleep 30
# 2. 重新启用分片分配
curl -k -X PUT "https://localhost:9200/_cluster/settings" \
-u elastic:你的密码 \
-H 'Content-Type: application/json' \
-d '{
"persistent": {
"cluster.routing.allocation.enable": null
}
}'
# 3. 验证集群健康
curl -k -u elastic:你的密码 "https://localhost:9200/_cluster/health?pretty"15. 附录
15.1 常用端口
| 端口 | 用途 |
|---|---|
| 9200 | HTTP REST API |
| 9300 | 节点间通信(Transport) |
15.2 重要文件路径
| 类型 | RPM/DEB 路径 | tar.gz 路径 |
|---|---|---|
| 主目录 | /usr/share/elasticsearch | /opt/elasticsearch |
| 配置文件 | /etc/elasticsearch | /opt/elasticsearch/config |
| 数据目录 | /var/lib/elasticsearch | /opt/elasticsearch/data |
| 日志目录 | /var/log/elasticsearch | /opt/elasticsearch/logs |
| 插件目录 | /usr/share/elasticsearch/plugins | /opt/elasticsearch/plugins |
| 证书目录 | /etc/elasticsearch/certs | /opt/elasticsearch/config/certs |
15.3 环境变量
# 添加到 /etc/profile 或 ~/.bashrc
export ES_HOME=/usr/share/elasticsearch
export ES_PATH_CONF=/etc/elasticsearch
export PATH=$PATH:$ES_HOME/bin15.4 有用的资源
- 官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html
- 中文社区:https://elasticsearch.cn/
- GitHub:https://github.com/elastic/elasticsearch
- 讨论论坛:https://discuss.elastic.co/
15.5 快速命令参考
# 查看所有索引
curl -k -u elastic:密码 "https://localhost:9200/_cat/indices?v"
# 查看集群健康
curl -k -u elastic:密码 "https://localhost:9200/_cluster/health?pretty"
# 查看节点信息
curl -k -u elastic:密码 "https://localhost:9200/_cat/nodes?v"
# 查看分片分配
curl -k -u elastic:密码 "https://localhost:9200/_cat/shards?v"
# 查看正在执行的任务
curl -k -u elastic:密码 "https://localhost:9200/_tasks?pretty"
# 查看插件列表
curl -k -u elastic:密码 "https://localhost:9200/_cat/plugins?v"
# 查看索引模板
curl -k -u elastic:密码 "https://localhost:9200/_cat/templates?v"
# 查看别名
curl -k -u elastic:密码 "https://localhost:9200/_cat/aliases?v"结语
本文档详细介绍了 Elasticsearch 在 Linux 服务器上的完整安装和使用流程。从环境准备、安装配置、基本使用到性能优化和故障排查,涵盖了日常运维中的常见场景。
在生产环境中使用 Elasticsearch 时,建议:
- 合理配置集群,至少 3 个主节点
- 定期备份重要数据
- 监控集群健康状态和性能指标
- 根据业务需求调整索引策略
- 保持软件版本更新

站点网址:https://www.jiafeng.fun
站点头像:https://www.jiafeng.fun/favicon.ico
站点简介(可无):个人博客,前端技术分享