Deploying Node.js Services: Process Management, Reverse Proxies, and Graceful Shutdown
🎯 Introduction
By the end of this article, you will be able to coordinate startup, request forwarding, and shutdown and distinguish application and platform responsibilities.
⚙️ Provide a health check
Reuse config.mjs from the engineering section and error-handler.mjs from the shared exception handling article. Create service.mjs:
import express from 'express';
import { setTimeout as delay } from 'node:timers/promises';
import { config } from './config.mjs';
import { errorHandler } from './error-handler.mjs';
const app = express();
let stopping = false;
Stop accepting new business operations during shutdown:
app.use((req, res, next) => {
if (stopping) return res.status(503).json({ error: 'Service is shutting down' });
next();
});
Add a health check:
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
/health proves that the HTTP service responds. If the platform needs to determine readiness for business traffic, also check required dependencies such as the database, with bounded check durations.
⏳ Observe shutdown with a slow endpoint
Add an endpoint that waits 1.5 seconds:
app.get('/slow', async (req, res) => {
await delay(1500);
res.json({ message: 'Processing complete' });
});
app.use(errorHandler);
This lets you observe whether accepted requests complete before shutdown. Express 5 forwards asynchronous failures to error middleware.
🔌 Listen and set request reception deadlines
const server = app.listen(config.port, '127.0.0.1', () => {
console.log('Service started', process.pid);
});
server.headersTimeout = 10_000;
server.requestTimeout = 30_000;
app.listen returns the HTTP server. headersTimeout limits the time to receive complete headers; requestTimeout limits the time to receive the complete request. Neither limits business function execution. Database and external calls still need their own timeouts.
Listening locally suits a reverse proxy on the same machine. Containers accessed through port mappings can listen on 0.0.0.0, with container and network rules restricting external entry points.
🛑 Graceful shutdown waits first, then enforces a deadline
Graceful shutdown stops accepting new work, gives accepted requests time to finish, then releases resources. First add the deadline fallback:
function forceStop() {
console.error('Shutdown deadline exceeded');
server.closeAllConnections();
process.exit(1);
}
Then add normal shutdown:
function shutdown() {
if (stopping) return;
stopping = true;
const deadline = setTimeout(forceStop, 5000);
server.close(() => {
clearTimeout(deadline);
console.log('HTTP requests have finished');
});
}
server.close stops accepting new connections and waits for current HTTP requests. Normal completion clears the fallback timer; only after five seconds are requests forcibly interrupted. Coordinate the real shutdown deadline with allowed request durations.
📣 Receive and verify shutdown signals
Continue with signal handlers:
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
Deployment platforms commonly send SIGTERM; Ctrl+C usually triggers SIGINT. After starting the server, request /slow from another terminal and press Ctrl+C before its 1.5 seconds elapse. The client should still receive 200 and “Processing complete”, then the service should exit.
node --env-file=.env service.mjs
curl -i http://127.0.0.1:3000/slow
If a database is used, close its pool after HTTP requests finish. Explicitly notify and close SSE or WebSocket connections rather than expecting all connections to finish automatically. Uncaught serious exceptions must also be logged and handled through external restart management rather than merely printed while normal operation continues.
🧰 Let process management handle recovery
Linux systemd can start the service at boot and restart it after failures. This example service unit belongs on a prepared Linux server; it is not a local macOS command.
[Unit]
Description=Backend demo
After=network.target
[Service]
Type=exec
User=nodeapp
WorkingDirectory=/srv/backend-demo
ExecStart=/opt/node/bin/node --env-file=/srv/backend-demo/.env service.mjs
Restart=on-failure
RestartSec=3
TimeoutStopSec=10
[Install]
WantedBy=multi-user.target
Before use, create the low-privilege nodeapp account, deploy files with necessary permissions, and replace the Node path with its actual absolute server path. The app's five-second deadline is shorter than the platform's ten seconds so cleanup can finish first. Do not run ordinary APIs permanently as an administrator.
Install the unit under /etc/systemd/system/, then reload and enable it:
sudo systemctl daemon-reload
sudo systemctl enable --now backend-demo
Inspect status and logs:
systemctl status backend-demo
journalctl -u backend-demo -f
Even after the process is running, request /health to verify responses. If it fails, inspect paths, account permissions, and configuration rather than repeatedly restarting.
🌐 Use a reverse proxy as the public entry point
Nginx receives external requests and forwards them to local Node.js. On a server with Nginx installed, place this HTTP forwarding configuration in a file loaded inside the http context:
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
}
Without an additional path, proxy_pass preserves the original request path. This example only demonstrates forwarding. A production login service also needs a valid domain certificate, HTTPS, and HTTP-to-HTTPS redirection. Never transmit passwords over the public internet in plaintext.
Check configuration before reloading:
sudo nginx -t
sudo systemctl reload nginx
If local /health succeeds but the domain returns 502, check the proxy destination and listening address. If the page reports CORS, inspect browser origin permissions. These problems do not all mean “Node.js is not running.”
❓ Questions and Answers
Q1: Can Node.js restart itself through its own code after crashing?
Use external process management. Once the application process ends, its internal timers no longer run.
Q2: Why not exit immediately on a signal?
That can interrupt responses or data writes. Waiting for accepted requests reduces interruption, but the wait must have a deadline.
Q3: Can a reverse proxy replace authentication?
Ordinary forwarding cannot. It handles the network entry point; business endpoints still need identity and permission checks.
🧪 Practice
Verify that a slow request completes during shutdown. Then set the demonstration delay to eight seconds and verify that the five-second fallback interrupts it. Restore the original value afterward and keep test configuration out of production.
// Write your code or record your verification results here
