How to do graceful stop for koajs server?


There are a lot of examples of graceful stop for expressjs, how can I achieve the same for koajs?

I would like to disconnect database connections as well

I have a mongoose database connection, and 2 oracle db connection (


I created an npm package http-graceful-shutdown ( some time ago. This works perfectly with http, express and koa. As you want to add also your own cleanup stuff, I modified the package, so that you now can add your own cleanup function, that will be called on shutdown. So basically this package handles all http shutdown things plus calling your cleanup function (if provided in the options):

const koa = require('koa');
const gracefulShutdown = require('http-graceful-shutdown');
const app = new koa();

server = app.listen(...); // app can be an express OR koa app

// your personal cleanup function - this one takes one second to complete
function cleanup() {
  return new Promise((resolve) => {
    console.log('... in cleanup')
    setTimeout(function() {
        console.log('... cleanup finished');
    }, 1000)       

// this enables the graceful shutdown with advanced options
        signals: 'SIGINT SIGTERM',
        timeout: 30000,
        development: false,
        onShutdown: cleanup,
        finally: function() {
            console.log('Server gracefulls shutted down.....')

Answered By – Sebastian Hildebrandt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published