title: How do I shut down my Express server gracefully when its process is killed?
body: <p>When running my Express application in production, I want to shut down the server gracefully when its process is killed (i.e. a <code>SIGTERM</code> or <code>SIGINT</code> is sent).</p>
  <p>Here is a simplified version of my code:</p>
  <pre><code>const express = require('express');
  
  const app = express();
  
  app.get('/', (req, res) =&gt; res.json({ ping: true }));
  
  const server = app.listen(3000, () =&gt; console.log('Running…'));
  
  setInterval(() =&gt; server.getConnections(
      (err, connections) =&gt; console.log(`${connections} connections currently open`)
  ), 1000);
  
  process.on('SIGTERM', shutDown);
  process.on('SIGINT', shutDown);
  
  function shutDown() {
      console.log('Received kill signal, shutting down gracefully');
      server.close(() =&gt; {
          console.log('Closed out remaining connections');
          process.exit(0);
      });
  
      setTimeout(() =&gt; {
          console.error('Could not close connections in time, forcefully shutting down');
          process.exit(1);
      }, 10000);
  }
  </code></pre>
  <p>When I run it and call the URL http://localhost:3000/ in a browser, the log statement in the setInterval function will keep printing “1 connection currently open” until I actually close the browser window. Even closing the tab will keep the connection open, apparently.</p>
  <p>So when I kill my server by hitting Ctrl+C, it will run into the timeout and print “Could not close connections” after 10 seconds, all the while continuing to print “1 connection open”.</p>
  <p>Only if I close the browser window before killing the process I get the “closed out remaining connections” message.</p>
  <p><strong>What am I missing here? What is the proper way to shut down an Express server gracefully?</strong></p>