Implantação de Cluster Elasticsearch e Balanceamento de Carga com Docker e Nginx

Preparação do Ambiente Docker

Para iniciar a configuração, é necessário garantir que o Docker esteja instalado e atualizado no sistema operacional. O processo abaixo utiliza o gerenciador de pacotes YUM para ambientes baseados em RedHat/CentOS.

# Atualizar repositórios e instalar Docker
sudo yum update -y
sudo yum remove docker-ce -y
sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install -y docker-ce docker-ce-cli containerd.io

# Iniciar e habilitar o serviço do Docker
sudo systemctl start docker
sudo systemctl enable docker

# Configurar acelerador de espelho do Docker
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://registry.docker-cn.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

Ajustes de Sistema e Estrutura de Diretórios

O Elasticsearch exige um ajuste no limite de áreas de memória mapeada do kernel. Além disso, precisamos criar a estrutura de diretórios para persistir dados, configurações e plugins de cada nó do cluster.

# Ajustar limite de memória mapeada
echo "vm.max_map_count=262144" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

# Criar diretórios para 3 nós (Master e Data nodes)
for i in 1 2 3; do
  sudo mkdir -p /opt/es_cluster/node${i}/{data,plugins,config}
  sudo chmod -R 777 /opt/es_cluster/node${i}
done

Configuração dos Nós Elasticsearch

Crie os arquivos de configuração elasticsearch.yml para cada nó. Utilizaremos a versão 7.17.0 e a sintaxe moderna de descoberta de nós.

Nó 1 (Master e Data)

# /opt/es_cluster/node1/config/elasticsearch.yml
cluster.name: es-production-cluster
node.name: es-node-master
node.master: true
node.data: true
path.data: /usr/share/elasticsearch/data
path.logs: /usr/share/elasticsearch/logs
network.host: 0.0.0.0
http.port: 9200
transport.port: 9300
discovery.seed_hosts: ["192.168.10.50:9301", "192.168.10.50:9302", "192.168.10.50:9303"]
cluster.initial_master_nodes: ["es-node-master"]
http.cors.enabled: true
http.cors.allow-origin: "*"

Nó 2 (Data)

# /opt/es_cluster/node2/config/elasticsearch.yml
cluster.name: es-production-cluster
node.name: es-node-data-1
node.master: false
node.data: true
path.data: /usr/share/elasticsearch/data
path.logs: /usr/share/elasticsearch/logs
network.host: 0.0.0.0
http.port: 9200
transport.port: 9300
discovery.seed_hosts: ["192.168.10.50:9301", "192.168.10.50:9302", "192.168.10.50:9303"]
http.cors.enabled: true
http.cors.allow-origin: "*"

Nó 3 (Data)

# /opt/es_cluster/node3/config/elasticsearch.yml
cluster.name: es-production-cluster
node.name: es-node-data-2
node.master: false
node.data: true
path.data: /usr/share/elasticsearch/data
path.logs: /usr/share/elasticsearch/logs
network.host: 0.0.0.0
http.port: 9200
transport.port: 9300
discovery.seed_hosts: ["192.168.10.50:9301", "192.168.10.50:9302", "192.168.10.50:9303"]
http.cors.enabled: true
http.cors.allow-origin: "*"

Execução dos Contêineres

Inicie os contêineres mapeando as portas do host para as portas internas do Elasticsearch. O nó 1 responderá na porta 9201, o nó 2 na 9202 e o nó 3 na 9203.

# Iniciar Nó 1
docker run -d --name es-node-master \
  -p 9201:9200 -p 9301:9300 \
  -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
  -v /opt/es_cluster/node1/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml \
  -v /opt/es_cluster/node1/data:/usr/share/elasticsearch/data \
  -v /opt/es_cluster/node1/plugins:/usr/share/elasticsearch/plugins \
  --restart=always \
  elasticsearch:7.17.0

# Iniciar Nó 2
docker run -d --name es-node-data-1 \
  -p 9202:9200 -p 9302:9300 \
  -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
  -v /opt/es_cluster/node2/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml \
  -v /opt/es_cluster/node2/data:/usr/share/elasticsearch/data \
  -v /opt/es_cluster/node2/plugins:/usr/share/elasticsearch/plugins \
  --restart=always \
  elasticsearch:7.17.0

# Iniciar Nó 3
docker run -d --name es-node-data-2 \
  -p 9203:9200 -p 9303:9300 \
  -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
  -v /opt/es_cluster/node3/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml \
  -v /opt/es_cluster/node3/data:/usr/share/elasticsearch/data \
  -v /opt/es_cluster/node3/plugins:/usr/share/elasticsearch/plugins \
  --restart=always \
  elasticsearch:7.17.0

Configuração do Firewall

Libere as portas de comunicação HTTP e de trensporte no firewall do sistema para permitir a conexão externa e entre os nós.

sudo firewall-cmd --zone=public --add-port=9201-9203/tcp --permanent
sudo firewall-cmd --zone=public --add-port=9301-9303/tcp --permanent
sudo firewall-cmd --reload

Instalação de Plugins e Ferramnetas de Gestão

Para suportar a análise de texto em português e chinês, instalaremos o plugin IK. Após a instalação no nó mestre, os arquivos serão copiados para os outros nós.

# Acessar o contêiner mestre
docker exec -it es-node-master bash

# Instalar o plugin IK
./bin/elasticsearch-plugin install -b https://get.infini.cloud/elasticsearch/analysis-ik/7.17.0
exit

# Copiar o plugin para os nós de dados
sudo cp -r /opt/es_cluster/node1/plugins/analysis-ik /opt/es_cluster/node2/plugins/
sudo cp -r /opt/es_cluster/node1/plugins/analysis-ik /opt/es_cluster/node3/plugins/

# Reiniciar os nós de dados para carregar o plugin
docker restart es-node-data-1 es-node-data-2

Para facilitar a visualização e gestão dos índices, suba um contêiner com o elasticsearch-head.

docker run -d --name es-head-ui \
  -p 9100:9100 \
  mobz/elasticsearch-head:5

Balanceamento de Carga com Nginx

Para distribuir as requisições de forma equilibrada entre os nós do cluster, configure o Nginx utilizando o algoritmo least_conn.

# /etc/nginx/conf.d/es_cluster.conf
upstream elasticsearch_backend {
    least_conn;
    server 192.168.10.50:9201;
    server 192.168.10.50:9202;
    server 192.168.10.50:9203;
    keepalive 64;
}

server {
    listen 9200;
    server_name es.local;
    underscores_in_headers on;

    location / {
        proxy_pass http://elasticsearch_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "Keep-Alive";
        proxy_set_header Proxy-Connection "Keep-Alive";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Recarregue as configurações do Nginx para aplicar as alterações. A partir de agora, as requisições enviadas para a porta 9200 do host serão distribuídas dinamicamente entre os três nós do cluster Elasticsearch.

sudo nginx -s reload

Tags: Docker elasticsearch nginx load-balancing Linux

Publicado em 8-11 22:46