Skip to content

Commit

Permalink
fix: gracefully shutdown standalone server
Browse files Browse the repository at this point in the history
- Both the standalone server and the startServer function it calls
  attempt to stop the server on SIGINT and SIGTERM in different ways.
  This lets server.js yield to startServer
- The cleanup function in startServer was not waiting for the server to
  close before calling process.exit. This lets it wait for any in-flight
  requests to finish processing before exiting the process

fixes: #53661
  • Loading branch information
redbmk committed Dec 13, 2023
1 parent e3b0294 commit 3db2e2c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 9 deletions.
7 changes: 0 additions & 7 deletions packages/next/src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2037,13 +2037,6 @@ const dir = path.join(__dirname)
process.env.NODE_ENV = 'production'
process.chdir(__dirname)
// 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('SIGTERM', () => process.exit(0))
process.on('SIGINT', () => process.exit(0))
}
const currentPort = parseInt(process.env.PORT, 10) || 3000
const hostname = process.env.HOSTNAME || '0.0.0.0'
Expand Down
8 changes: 6 additions & 2 deletions packages/next/src/server/lib/start-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,10 @@ export async function startServer(
try {
const cleanup = (code: number | null) => {
debug('start-server process cleanup')
server.close()
process.exit(code ?? 0)
Log.info('Shutting down server')
server.close(() => {
process.exit(code ?? 0)
})
}
const exception = (err: Error) => {
if (isPostpone(err)) {
Expand All @@ -280,6 +282,8 @@ export async function startServer(
console.error(err)
}
process.on('exit', (code) => cleanup(code))
// 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) {
// callback value is signal string, exit with 0
process.on('SIGINT', () => cleanup(0))
Expand Down

0 comments on commit 3db2e2c

Please sign in to comment.