Separate operational errors from programmer defects, expose liveness and readiness correctly, stop accepting traffic on termination, and bound graceful shutdown.
What you will build
This tutorial produces a working, verifiable result rather than a command list. Read each command before running it, keep configuration in version control without secrets, and record the versions used for repeatable deployment.
1. Prepare the project
npm install express@5
export PORT=3000
Run preparation commands as an unprivileged application user unless a command explicitly requires sudo. A clean working tree and lockfile make rollback much easier.
2. Implement the solution
import express from 'express';
const app=express(); let ready=true;
app.get('/livez',(req,res)=>res.json({status:'alive'}));
app.get('/readyz',(req,res)=>ready?res.json({status:'ready'}):res.status(503).json({status:'draining'}));
app.use((err,req,res,next)=>{console.error(err); if(res.headersSent)return next(err); res.status(500).json({error:'internal_error'});});
const server=app.listen(Number(process.env.PORT??3000));
async function shutdown(signal){console.log({signal},'shutdown');ready=false;server.close(()=>process.exit(0));setTimeout(()=>process.exit(1),10_000).unref();}
for(const s of ['SIGINT','SIGTERM']) process.once(s,()=>shutdown(s));
process.on('unhandledRejection',error=>{console.error(error);shutdown('unhandledRejection');});
Save the example in the filename indicated by its comment or surrounding instructions. Treat it as a minimal baseline: production applications should separate transport, business logic, persistence, and configuration into testable modules.
3. Verify end to end
node server.js & APP_PID=$!
curl -fsS http://127.0.0.1:3000/livez
curl -fsS http://127.0.0.1:3000/readyz
kill -TERM "$APP_PID"
wait "$APP_PID"
Verification should cover both process state and a real request or data operation. A process that is merely running is not necessarily ready to serve traffic.
4. Troubleshooting and production notes
Liveness should answer whether the process is functioning; readiness should answer whether it can serve traffic. Do not make liveness depend on every remote service. During shutdown, mark unready first and close HTTP, database, queue, and telemetry resources within the platform grace period.
Production checklist
- The supported Node.js LTS version and dependency lockfile are recorded.
- Configuration is validated at startup and secrets are stored outside source control.
- Input limits, authentication, authorization, timeouts, and error boundaries are explicit.
- Logs identify a request without exposing credentials or personal data.
- Health checks, graceful termination, resource limits, backup, and rollback have been tested.
Reference: official topic documentation. For production version selection, use a supported LTS line from the Node.js release schedule.