Nginx 是一个高性能的 HTTP 服务器和反向代理服务器,广泛用于负载均衡、缓存、SSL 终端和服务代理等场景。本篇将尝试使用 Nginx 代理 Easysearch 服务,方法同样适用于 Elasticsearch 和 Opensearch。
测试环境
- Easysearch 集群版本为 1.10.0,3 个节点
- Nginx 版本为 1.21.5
Nginx
计划使用 Nginx 将请求均匀分发到所有节点,关键配置如下:
http {upstream es-cluster {server 192.168.56.102:9200;server 192.168.56.102:9201;server 192.168.56.102:9202;}log_format es_log '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''upstream: $upstream_addr';# 配置代理服务器信息server {listen 80;server_name localhost;location / {proxy_pass https://es-cluster;#proxy_http_version 1.1;#proxy_set_header Connection "";# 添加 Basic Auth 认证auth_basic "Restricted Access"; # 认证提示信息auth_basic_user_file /etc/nginx/.htpasswd; # 认证文件路径# 使用自定义日志格式access_log /var/log/nginx/elasticsearch_access.log es_log;}}
}
由于 Easysearch 开启了认证功能,需要 给 Nginx 创建一个认证文件。示例为 Nginx 配置了 admin 用户,大家根据情况自行调整。
echo "admin:$(openssl passwd -crypt yourpassword)" | sudo tee /etc/nginx/.htpasswd
经过上面的配置,Nginx 会将访问日志记录在 /var/log/nginx/elasticsearch_access.log 中。
至此 Nginx 已经配置完毕,启动 Nginx 服务。
sudo systemctl start nginx
测试
我们使用 curl 命令连续向 Nginx 发送 6 个查询请求,看看请求是否发送到 Easysearch 的所有节点。
curl localhost:80/infini/_search -uadmin:56939c1f6527d1a0d51c
可以看到,如我们期待那样查询请求在所有节点间轮询。