Serve a health check endpoint
Serve separate liveness and readiness endpoints from a Node.js 24 http server, returning 503 while a dependency is down or the process is shutting down.
A load balancer or Kubernetes asks two different questions: is the process alive, and should it get traffic right now. Answer them on two paths, or a slow database restarts healthy pods.
import http from 'node:http';
let shuttingDown = false;
const checkDatabase = async () => true; // replace with a cheap SELECT 1
http.createServer(async (req, res) => {
if (req.url === '/livez') return res.end('ok');
if (req.url === '/readyz') {
const dbOk = await checkDatabase().catch(() => false);
const ready = dbOk && !shuttingDown;
res.writeHead(ready ? 200 : 503, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ db: dbOk, shuttingDown }));
}
res.end('app');
}).listen(3000);
process.on('SIGTERM', () => { shuttingDown = true; });$ curl -si localhost:3000/readyz | head -1
HTTP/1.1 200 OK
$ kill -TERM <pid>; curl -s localhost:3000/readyz
{"db":true,"shuttingDown":true}/livez checks nothing but that the event loop answers, so it fails only when the process is truly stuck, and that is the one failure a restart fixes. /readyz checks dependencies and returns 503 when one is down, which takes the instance out of rotation without killing it. Flipping readiness on SIGTERM lets the balancer drain traffic before the server stops. See liveness and readiness probes.
Keep both endpoints cheap and quick, since they run every few seconds, and do not put a database call in the liveness check. Do not expose version strings or internal hostnames on a public health path. The SIGTERM handler here only flips the flag; closing the server is the next step.