shutgrace
Graceful shutdown of Node.js servers with SQL database
The shutgrace package helps you gracefully shut down a Node.js server that connects to a SQL database.
Setup
Install the package:
npm install shutgrace
Usage
import express from 'express';
import gracefulShutdown from 'shutgrace';
import pinoLogger from 'lib/logger.js';
import { AppDataSource } from 'config/appDataSource.js'; // example TypeORM data source; optional
const app = express()
const port = 3000
AppDataSource.initialize()
app.get('/', (req, res) => {
res.send('Hello World!')
})
const server = app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
process.on('SIGINT', () => gracefulShutdown('SIGINT', server, { dataSource: AppDataSource, logger: pinoLogger }));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM', server, { dataSource: AppDataSource, logger: pinoLogger }));
What happens on shutdown
- The server stops accepting connections. Requests already being handled are left to finish, and connections are closed as they become idle.
- Connections still open after
timeout milliseconds are closed forcibly.
- The data source is destroyed, so the requests of step 1 can still use it. It gets
timeout milliseconds as well.
- The process exits: with code 0, or with code 1 if a step failed.
gracefulShutdown ends the process itself, so code placed after it does not run. A signal that arrives while a shutdown is under way does not start a second one.
Optional arguments
- "dataSource": needs to respond to
destroy() (ex. AppDataSource).
- "logger": needs to respond to
error({ err }, message) (ex. Pino). Without it, errors go to console.error.
- "timeout": milliseconds given to open connections, and then to the data source, to close. Defaults to 2000.
Output
Progress is written to stdout. On a terminal the steps overwrite one line; without one (service manager, container, pipe) each step is written on its own line.
TypeScript Support
This package includes TypeScript type definitions. If you use TypeScript, you automatically get type-checking for the gracefulShutdown function.
License
This project is licensed under the MIT License.
Package URL
https://www.npmjs.com/package/shutgrace
Code repository
https://bitbucket.org/endeavia/shutgrace/src/master/
Author
Tamás Kamarás