Skip to content

Instantly share code, notes, and snippets.

@coopermaruyama
Last active January 16, 2024 02:51
Show Gist options
  • Save coopermaruyama/c6cb469aecc30379e60897ab742f5408 to your computer and use it in GitHub Desktop.
Save coopermaruyama/c6cb469aecc30379e60897ab742f5408 to your computer and use it in GitHub Desktop.
Go-Ethereum (Geth) NGINX Health Check (Ubuntu)

Uses NGINX's njs module to query geth's eth_syncing RPC endpoint. Considered as "healthy" only when the syncing attribute is false.

This is useful if you are managing a cluster of geth nodes behind a load balancer and need a compatible healthcheck.

  1. Create a directory to store our njs script
$ mkdir /etc/nginx/njs
  1. Create file /etc/nginx/njs/health.js with the following:

If you have vhost set in geth, make sure <OPTIONAL_HOST> matches this value. otherwise you can remove the Host header.

async function health(r) {
  let res = await ngx.fetch('http://127.0.0.1:8545', {
    method: 'POST',
    headers: { Host: '<OPTIONAL_HOST>', 'Content-Type': 'application/json' },
    body: '{"jsonrpc": "2.0", "id": 1, "method":"eth_syncing", "params": [] }'
  });
  let body = await res.json();
  if (body.result) {
    r.return(500, 'not synced');
    return;
  } else {
    r.return(200, 'OK');
    return;
  }
}

export default {health}
  1. Install njs module for nginx

# (Optional) Backup your current nginx.conf (Sometimes it can be overwritten by installing nginx)
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

# Install dependencies
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring

# Get GPG key
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null


# Setup apt repo
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list
    
# Install
sudo apt update && sudo apt install nginx-module-njs
  1. Enable njs

In /etc/nginx/nginx.conf add:

load_module modules/ngx_http_js_module.so;
load_module modules/ngx_stream_js_module.so;
  1. In /etc/nginx/sites-available/xxx add
 js_path "/etc/nginx/njs/";
js_import main from health.js;
location /health {
    js_content main.health;
}
  1. Make sure config is ok and reload:
sudo nginx -t
sudo service nginx reload

Now, GET /health will return a 500 status code when not synced, or 200 if healthy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment