Docker Graceful Shutdown on SIGTERM

Handle Docker stop signals in Node so in-flight requests drain, background jobs checkpoint, and the process exits within the grace period.

JavascriptNodeResilience

Code

javascriptsnippet
29 lines
import fastify from 'fastify';

const app = fastify({ logger: true });
let shuttingDown = false;

app.get('/live', async () => ({ ready: !shuttingDown }));
app.post('/jobs', async () => ({ queued: true }));

const server = await app.listen({ port: 3000, host: '0.0.0.0' });

async function shutdown(signal) {
  shuttingDown = true;
  console.log('received', signal, 'draining connections');

  const deadline = Date.now() + 20_000;
  await app.close({ timeout: 15_000 });

  if (Date.now() > deadline) {
    console.warn('grace period exceeded, forcing exit');
  }
  process.exit(0);
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));

// Dockerfile 用途提示:
// STOPSIGNAL SIGTERM 让 docker stop 发送可捕获信号而非默认逻辑
console.log('docker-ready on port 3000');

Inside the snippet

Docker Graceful Shutdown on SIGTERM comes down to the function shutdown.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What to watch for

  • Dependency check: fastify — not built-in, must be present in the project.

Putting it to use

The signature doing the main work is async function shutdown(signal)

Look for the received, grace period exceeded, forcing exit, docker-ready on port 3000 prefixes once the file starts running; each one ties a printed line to the step that produced it.

Core lines

const server = await app.listen({ port: 3000, host: '0.0.0.0' });
app.get('/live', async () => ({ ready: !shuttingDown }));
app.post('/jobs', async () => ({ queued: true }));

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `fastify`. Without it the snippet will not load.