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.
Code
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');Report a problem with this exampleOpens a pre-filled issue on GitHub.