diff --git a/docs/01-app/02-guides/self-hosting.mdx b/docs/01-app/02-guides/self-hosting.mdx index d1795dd526a9e..f161a725d0f38 100644 --- a/docs/01-app/02-guides/self-hosting.mdx +++ b/docs/01-app/02-guides/self-hosting.mdx @@ -253,16 +253,23 @@ You can set the env variable `NEXT_MANUAL_SIG_HANDLE` to `true` and then registe } ``` -```js filename="pages/_document.js" +```js filename="app/layout.tsx" if (process.env.NEXT_MANUAL_SIG_HANDLE) { - process.on('SIGTERM', () => { - console.log('Received SIGTERM: cleaning up') - process.exit(0) - }) - process.on('SIGINT', () => { - console.log('Received SIGINT: cleaning up') - process.exit(0) - }) + let sigHandled = false + const handleSig = () => { + if (sigHandled) return + sigHandled = true + + console.log('Received SIGINT/SIGTERM: cleaning up') + + // Run clean up + + // Trigger Next.js graceful shutdown + process.env.NEXT_MANUAL_SIG_HANDLE = false + process.emit('SIGTERM') + } + process.on('SIGTERM', handleSig) + process.on('SIGINT', handleSig) } ``` diff --git a/packages/next/src/server/lib/start-server.ts b/packages/next/src/server/lib/start-server.ts index 9d16195a4f364..f199204cb5cdb 100644 --- a/packages/next/src/server/lib/start-server.ts +++ b/packages/next/src/server/lib/start-server.ts @@ -386,6 +386,9 @@ export async function startServer( let cleanupStarted = false let closeUpgraded: (() => void) | null = null const cleanup = () => { + // Allow the graceful termination to be manually configurable + if (process.env.NEXT_MANUAL_SIG_HANDLE) return + if (cleanupStarted) { // We can get duplicate signals, e.g. when `ctrl+c` is used in an // interactive shell (i.e. bash, zsh), the shell will recursively @@ -422,11 +425,8 @@ export async function startServer( } // Make sure commands gracefully respect termination signals (e.g. from Docker) - // Allow the graceful termination to be manually configurable - if (!process.env.NEXT_MANUAL_SIG_HANDLE) { - process.on('SIGINT', cleanup) - process.on('SIGTERM', cleanup) - } + process.on('SIGINT', cleanup) + process.on('SIGTERM', cleanup) const initResult = await getRequestHandlers({ dir,