The process global object provides information about, and control over, the current Node.js runtime process instance. It allows reading environment variables, terminating processes, receiving OS signals, and reading standard I/O streams.
flowchart LR
A["OS / Docker / K8s Manager"] -->|"SIGTERM / SIGINT signal"| B["process.on('SIGTERM') Listener"]
B --> C["Graceful Shutdown: Close DB & Server"]
C --> D["process.exit(0)"]
import http from 'node:http';
// 1. Inspect Environment Variables & Arguments
const PORT = process.env.PORT || 5000;
const NODE_ENV = process.env.NODE_ENV || 'development';
console.log(`Starting process in [${NODE_ENV}] mode on PID ${process.pid}`);
console.log('CLI Arguments:', process.argv.slice(2));
// 2. Graceful Shutdown HTTP Server Setup
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Server Active');
});
server.listen(PORT, () => console.log(`Server live on port ${PORT}`));
// Graceful Termination Signal Listener
function handleShutdown(signal) {
console.log(`
Received ${signal}. Initiating graceful shutdown...`);
server.close(() => {
console.log('HTTP Server closed. Database connections released.');
process.exit(0); // Exit code 0 indicates clean exit
});
// Force terminate if graceful cleanup hangs
setTimeout(() => {
console.error('Forced shutdown due to timeout.');
process.exit(1);
}, 10000).unref();
}
process.on('SIGINT', () => handleShutdown('SIGINT')); // Ctrl+C
process.on('SIGTERM', () => handleShutdown('SIGTERM')); // Container Stop Signal
0 for Success, 1 for Failures: Exit with process.exit(0) on clean shutdowns and non-zero (e.g. process.exit(1)) on unrecoverable errors.SIGTERM and SIGINT signals to close active database pools and complete pending HTTP requests before exiting..env Files in Production: Pass environment variables directly via host runtime containers or secret managers.Write code to listen for process.on('uncaughtException') and print the error message before exiting gracefully.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With