Elasticsearch "Connection refused" before the cluster reaches yellow in CI
Elasticsearch is slow to start (often 20-60s) while it loads, runs bootstrap checks, and forms the cluster. Connections before then are refused. Poll the _cluster/health endpoint until it reports yellow or green.
What this error means
Early requests to port 9200 fail with "Connection refused" or "Failed to connect", then succeed once the node has fully started.
curl: (7) Failed to connect to localhost port 9200: Connection refusedCommon causes
The node is still starting up
Elasticsearch performs significant initialization before binding 9200. On CI hardware this can take tens of seconds.
A naive port check or short sleep proceeds too early
A fixed sleep 5 or a TCP-only probe lets steps run before the cluster is query-ready.
How to fix it
Wait for cluster health to reach yellow
Poll the health endpoint with wait_for_status=yellow until it returns, which blocks until the cluster is usable.
until curl -s "http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=5s" \
| grep -qE '"status":"(yellow|green)"'; do
echo "waiting for elasticsearch"; sleep 3
doneUse a healthcheck on the cluster health endpoint
When running ES as a service container, gate steps on a curl healthcheck.
options: >-
--health-cmd "curl -fsS http://localhost:9200/_cluster/health || exit 1"
--health-interval 10s
--health-retries 12
--health-start-period 30sHow to prevent it
- Poll
_cluster/health?wait_for_status=yellowrather than a fixed sleep. - Allow a generous
--health-start-periodfor the slow first boot. - Raise
vm.max_map_countfirst so the node does not exit before starting.