Skip to content

Deploying an Elasticsearch 8.x 3-node cluster on Ubuntu 22.04 with TLS and S3 snapshots

Stand up a self-hosted Elasticsearch 8.x cluster on Ubuntu 22.04 — full installer with xpack security, TLS between nodes, transport and HTTP certificates, and an S3 snapshot repository.

Your search workload outgrew the single-node Elasticsearch the previous team installed two years ago. The JVM keeps fielding OOM kills during reindex, the only “backup” is a VM snapshot taken weekly, and you found out — the hard way — that an Elasticsearch index restored from a filesystem snapshot of a running node comes back corrupt about half the time. You need a three-node cluster with proper inter-node TLS, xpack security enforced, and a snapshot repository pointed at object storage so the next restore is a one-liner instead of an incident. This is the installer.

What’s happening

Elasticsearch 8 ships with security on by default — xpack.security.enabled is true from the first start, transport-layer TLS is mandatory between nodes, and HTTP needs at least basic auth. The good news is the defaults are sane; the bad news is most teams running a “quick test cluster” disable all three to get past the bootstrap, then forget to turn them back on. A production 3-node deployment needs: a shared certificate authority generated once on node 1, individual node certificates signed by that CA, a transport keystore on every node, an HTTP TLS keystore (often the same), an xpack.security.enrollment.enabled=true bootstrap on node 1 followed by enrollment tokens on node 2 and node 3, and a snapshot repository registered against S3-compatible storage with the access key stored in the Elasticsearch keystore rather than a config file. Skip the keystore step and your S3 credentials end up in a world-readable elasticsearch.yml; skip the dedicated discovery.seed_hosts plus cluster.initial_master_nodes pair on first boot and the cluster starts in single-node mode and refuses to admit peers later.

How to verify

Cluster health from any node, with the auto-generated elastic password:

ES_PASS=$(cat /etc/elasticsearch/.elastic-password)
curl -sk -u "elastic:${ES_PASS}" https://10.10.0.21:9200/_cluster/health?pretty
# {
#   "cluster_name" : "search-prod",
#   "status" : "green",
#   "number_of_nodes" : 3,
#   "active_primary_shards" : 12,
#   "unassigned_shards" : 0
# }

Node list with roles:

curl -sk -u "elastic:${ES_PASS}" \
  https://10.10.0.21:9200/_cat/nodes?v=true&h=ip,heap.percent,role,master,name

You should see three lines, one with * in the master column. If two nodes report *, you have a split-brain — usually caused by the wrong cluster.initial_master_nodes list on first boot.

Snapshot repository registered and reachable:

curl -sk -u "elastic:${ES_PASS}" https://10.10.0.21:9200/_snapshot/_all?pretty
curl -sk -u "elastic:${ES_PASS}" -XPOST \
  https://10.10.0.21:9200/_snapshot/s3-backup/_verify

The _verify call must return all three node UUIDs as confirmed writers. A single missing node means one of the data nodes can’t reach S3 — check egress on that VM, not Elasticsearch.

The fix

Save the script as /root/setup-es-node.sh and run it on each of the three nodes after editing the variables at the top. The script handles the full installer on Ubuntu 22.04: base hardening (UFW, fail2ban, unattended-upgrades, kernel limits), Java tuning via the bundled JDK, the official Elasticsearch APT repository pinned to 8.x, a shared CA generated on node 1 and copied to node 2 and 3 in a tar, transport and HTTP TLS keystores per node, xpack security plus enrollment, cluster.initial_master_nodes set only on the first boot, an S3 snapshot keystore entry, and a final wait-loop that fails loudly if the cluster doesn’t go green within five minutes.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Elasticsearch 8.x 3-node cluster installer
### Run on node 1 first (bootstrap=true), then copy /etc/elasticsearch/certs.tgz
### to nodes 2 and 3, then run on each node with bootstrap=false
### Snapshot repo lives on S3-compatible storage (Wasabi/Backblaze/MinIO/AWS)

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_NAME="es01"               # es01 / es02 / es03
NODE_IP="10.10.0.21"           # this node's private IP
PEER_IPS=("10.10.0.21" "10.10.0.22" "10.10.0.23")
PEER_NAMES=("es01" "es02" "es03")
CLUSTER_NAME="search-prod"
BOOTSTRAP_NODE="true"          # true ONLY on es01 (first boot)
ES_VERSION="8.13.4"

# Snapshot S3 settings (use Wasabi/Backblaze/MinIO endpoint or AWS)
S3_ENDPOINT="s3.us-east-2.wasabisys.com"
S3_BUCKET="acme-es-snapshots"
S3_ACCESS_KEY="CHANGE_ME"
S3_SECRET_KEY="CHANGE_ME"
S3_REGION="us-east-2"
# =====================

echo
echo "========================================"
echo "Elasticsearch node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

echo "==> Updating base OS"
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get -y upgrade
apt-get -y install curl wget gnupg apt-transport-https ca-certificates \
  ufw fail2ban unattended-upgrades chrony jq socat net-tools dnsutils \
  tar gzip openjdk-17-jre-headless

systemctl enable --now chrony

echo "==> Kernel/sysctl tuning for Elasticsearch"
cat > /etc/sysctl.d/99-elasticsearch.conf <<'SYSCTL'
vm.max_map_count = 262144
vm.swappiness = 1
fs.file-max = 2097152
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.ip_local_port_range = 10240 65535
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-elasticsearch.conf <<'LIMITS'
elasticsearch soft nofile 65535
elasticsearch hard nofile 65535
elasticsearch soft memlock unlimited
elasticsearch hard memlock unlimited
elasticsearch soft nproc 4096
elasticsearch hard nproc 4096
LIMITS

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart ssh

echo "==> UFW: allow SSH + Elasticsearch transport/HTTP from peers"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
for p in "${PEER_IPS[@]}"; do
  ufw allow from "$p" to any port 9200 proto tcp
  ufw allow from "$p" to any port 9300 proto tcp
done
ufw --force enable

cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Adding Elasticsearch APT repository (8.x)"
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | gpg --dearmor -o /usr/share/keyrings/elastic-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/elastic-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" \
  > /etc/apt/sources.list.d/elastic-8.x.list
apt-get update
apt-get -y install "elasticsearch=${ES_VERSION}"
apt-mark hold elasticsearch

echo "==> Writing /etc/elasticsearch/elasticsearch.yml"
SEED_HOSTS=$(printf ',"%s:9300"' "${PEER_IPS[@]}")
SEED_HOSTS="[${SEED_HOSTS:1}]"

INITIAL_MASTERS=""
if [[ "$BOOTSTRAP_NODE" == "true" ]]; then
  INITIAL_MASTERS=$(printf ',"%s"' "${PEER_NAMES[@]}")
  INITIAL_MASTERS="cluster.initial_master_nodes: [${INITIAL_MASTERS:1}]"
fi

cat > /etc/elasticsearch/elasticsearch.yml <<EOF
cluster.name: ${CLUSTER_NAME}
node.name: ${NODE_NAME}
node.roles: [ master, data, ingest ]

network.host: ${NODE_IP}
http.port: 9200
transport.port: 9300

discovery.seed_hosts: ${SEED_HOSTS}
${INITIAL_MASTERS}

path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
path.repo: /var/lib/elasticsearch/repo

bootstrap.memory_lock: true

xpack.security.enabled: true
xpack.security.enrollment.enabled: true

xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/transport.p12
  truststore.path: certs/transport.p12

xpack.security.http.ssl:
  enabled: true
  keystore.path: certs/http.p12

action.destructive_requires_name: true
indices.recovery.max_bytes_per_sec: 100mb
EOF

echo "==> JVM heap (50% RAM, capped at 31g)"
RAM_KB=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
HEAP_MB=$(( RAM_KB / 2 / 1024 ))
if (( HEAP_MB > 31744 )); then HEAP_MB=31744; fi
cat > /etc/elasticsearch/jvm.options.d/heap.options <<EOF
-Xms${HEAP_MB}m
-Xmx${HEAP_MB}m
EOF

mkdir -p /etc/elasticsearch/certs
chown -R elasticsearch:elasticsearch /etc/elasticsearch/certs
chmod 750 /etc/elasticsearch/certs

if [[ "$BOOTSTRAP_NODE" == "true" ]]; then
  echo "==> Generating CA + per-node TLS keystores (bootstrap node only)"
  cd /tmp
  rm -f ca.zip certs.zip ca.p12

  /usr/share/elasticsearch/bin/elasticsearch-certutil ca \
    --out /tmp/ca.p12 --pass "" --silent

  SAN_FLAGS=""
  for i in "${!PEER_NAMES[@]}"; do
    SAN_FLAGS+=" --name ${PEER_NAMES[$i]} --dns ${PEER_NAMES[$i]} --ip ${PEER_IPS[$i]}"
  done

  /usr/share/elasticsearch/bin/elasticsearch-certutil cert \
    --ca /tmp/ca.p12 --ca-pass "" \
    --multiple --pem --silent \
    --out /tmp/certs.zip \
    ${SAN_FLAGS}

  rm -rf /tmp/certs
  unzip -q /tmp/certs.zip -d /tmp/certs

  for i in "${!PEER_NAMES[@]}"; do
    N="${PEER_NAMES[$i]}"
    /usr/share/elasticsearch/bin/elasticsearch-certutil cert \
      --ca /tmp/ca.p12 --ca-pass "" \
      --name "$N" --dns "$N" --ip "${PEER_IPS[$i]}" \
      --out "/tmp/${N}.p12" --pass "" --silent
  done

  # Build the per-node bundle: each node gets its own transport.p12 and http.p12
  rm -rf /tmp/bundle
  for i in "${!PEER_NAMES[@]}"; do
    N="${PEER_NAMES[$i]}"
    mkdir -p "/tmp/bundle/${N}"
    cp "/tmp/${N}.p12" "/tmp/bundle/${N}/transport.p12"
    cp "/tmp/${N}.p12" "/tmp/bundle/${N}/http.p12"
    cp /tmp/ca.p12 "/tmp/bundle/${N}/ca.p12"
  done

  tar czf /etc/elasticsearch/certs.tgz -C /tmp/bundle .
  cp "/tmp/bundle/${NODE_NAME}/"*.p12 /etc/elasticsearch/certs/
  chown -R elasticsearch:elasticsearch /etc/elasticsearch/certs /etc/elasticsearch/certs.tgz
  chmod 640 /etc/elasticsearch/certs/*.p12 /etc/elasticsearch/certs.tgz

  echo
  echo "==> Copy /etc/elasticsearch/certs.tgz to nodes 2 and 3, extract"
  echo "==> Then on node 2/3: tar xzf certs.tgz -C /tmp/bundle && cp /tmp/bundle/<nodeN>/*.p12 /etc/elasticsearch/certs/"
  echo
else
  echo "==> Non-bootstrap node: expecting certs already placed in /etc/elasticsearch/certs/"
  for f in transport.p12 http.p12; do
    if [[ ! -f "/etc/elasticsearch/certs/${f}" ]]; then
      echo "Missing /etc/elasticsearch/certs/${f} — copy from bootstrap node before re-running."
      exit 1
    fi
  done
  chown -R elasticsearch:elasticsearch /etc/elasticsearch/certs
  chmod 640 /etc/elasticsearch/certs/*.p12
fi

echo "==> Snapshot S3 keystore entries"
ELASTIC_KEYSTORE=/usr/share/elasticsearch/bin/elasticsearch-keystore
echo -n "${S3_ACCESS_KEY}" | $ELASTIC_KEYSTORE add -x -f -s s3.client.default.access_key
echo -n "${S3_SECRET_KEY}" | $ELASTIC_KEYSTORE add -x -f -s s3.client.default.secret_key

echo "==> Enabling memlock in systemd unit"
mkdir -p /etc/systemd/system/elasticsearch.service.d
cat > /etc/systemd/system/elasticsearch.service.d/override.conf <<'OV'
[Service]
LimitMEMLOCK=infinity
LimitNOFILE=65535
OV

systemctl daemon-reload
systemctl enable elasticsearch
systemctl start elasticsearch

echo "==> Waiting for HTTPS on :9200"
for i in {1..60}; do
  if curl -sk "https://${NODE_IP}:9200" >/dev/null 2>&1; then break; fi
  sleep 3
done

if [[ "$BOOTSTRAP_NODE" == "true" ]]; then
  echo "==> Resetting elastic password on bootstrap node"
  ELASTIC_PASS=$(/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic -b -s 2>/dev/null || true)
  if [[ -z "$ELASTIC_PASS" ]]; then
    ELASTIC_PASS=$(/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic -b -s)
  fi
  echo "$ELASTIC_PASS" > /etc/elasticsearch/.elastic-password
  chmod 600 /etc/elasticsearch/.elastic-password
  chown root:root /etc/elasticsearch/.elastic-password

  echo "==> Registering S3 snapshot repository"
  for i in {1..30}; do
    if curl -sk -u "elastic:${ELASTIC_PASS}" "https://${NODE_IP}:9200/_cluster/health" >/dev/null; then break; fi
    sleep 2
  done

  curl -sk -u "elastic:${ELASTIC_PASS}" -XPUT \
    "https://${NODE_IP}:9200/_snapshot/s3-backup" \
    -H 'Content-Type: application/json' -d "{
      \"type\": \"s3\",
      \"settings\": {
        \"bucket\": \"${S3_BUCKET}\",
        \"endpoint\": \"${S3_ENDPOINT}\",
        \"region\": \"${S3_REGION}\",
        \"protocol\": \"https\",
        \"path_style_access\": true,
        \"compress\": true
      }
    }"
  echo
fi

echo
echo "========================================"
echo "DONE — ${NODE_NAME}"
echo "========================================"
echo
echo "Cluster health:"
if [[ -f /etc/elasticsearch/.elastic-password ]]; then
  ES_PASS=$(cat /etc/elasticsearch/.elastic-password)
  curl -sk -u "elastic:${ES_PASS}" "https://${NODE_IP}:9200/_cluster/health?pretty" || true
fi
echo
echo "Listeners:"
ss -lntp | grep -E ':(9200|9300)\b' || true
echo
echo "Next: repeat on the next node (bootstrap=false), having copied certs.tgz."

Make it executable and run on node 1 first:

chmod 700 /root/setup-es-node.sh
/root/setup-es-node.sh
# copy /etc/elasticsearch/certs.tgz to node 2 and node 3
# on each, extract the matching bundle into /etc/elasticsearch/certs/
# set BOOTSTRAP_NODE="false" and re-run

When all three are up, _cluster/health returns green. Schedule the first snapshot via SLM and a retention policy:

ES_PASS=$(cat /etc/elasticsearch/.elastic-password)
curl -sk -u "elastic:${ES_PASS}" -XPUT \
  "https://10.10.0.21:9200/_slm/policy/nightly" \
  -H 'Content-Type: application/json' -d '{
    "schedule": "0 30 1 * * ?",
    "name": "<nightly-{now/d}>",
    "repository": "s3-backup",
    "config": { "indices": ["*"], "include_global_state": true },
    "retention": { "expire_after": "30d", "min_count": 7, "max_count": 60 }
  }'

Run a restore drill against a sandbox cluster monthly — an SLM policy that has never been restored is a hypothesis. If the drill takes longer than your RTO target, raise indices.recovery.max_bytes_per_sec (defaults to 40mb in some 8.x builds) or move the snapshot repo to storage with better restore throughput.

For Elasticsearch you don’t have to operate yourself, our Cloud Compute team runs the cluster under Managed Cloud Ops with snapshot-integrity drills baked into the monitoring plane — start a scoping call.