Go服务启动时必须显式监听os.Interrupt和syscall.SIGTERM信号以实现优雅关闭,配合context.WithTimeout控制超时,调用http.Server.Shutdown()并检查ErrServerClosed,确保数据库、gRPC、消息消费者等所有组件支持context取消和资源清理,main函数需阻塞等待shutdown完成后再退出。
os.Interrupt 和 syscall.SIGTERM
Go 默认不会自动处理进程终止信号,不监听就直接 kill -15 会立刻退出,中间正在处理的 HTTP 请求、数据库事务、消息消费都会被粗暴中断。必须手动注册信号监听器,并配合 context.WithTimeout 控制关闭窗口。
os.Interrupt 对应 Ctrl+C(开发调试常用)syscall.SIGTERM 是 Kubernetes、systemd、docker stop 等生产环境的标准终止信号SIGTERM,本地调试按 Ctrl+C,少一个就无法优雅退出os.Exit(),要触发 shutdown 流程Shutdown() 必须带 context,且超时时间要合理http.Server.Shutdown() 是 Go 1.8+ 提供的唯一标准优雅关闭方式,但它不会自己等待,必须传入带超时的 context.Context,否则可能永远阻塞。
context.Background() 或 context.TODO(),它们没有取消机制srv.Shutdown() 后,仍需检查返回错误:ErrServerClosed 是正常关闭,其他错误(如网络中断)需记录日志ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("HTTP server shutdown error: %v", err)
}
HTTP Server 只是入口,背后还有数据库连接池、

db.Close()(它本身会等待活跃连接归还)server.GracefulStop()
Close() 或 Shutdown() 方法,且是否接受 contextselect 中监听 ctx.Done(),并执行清理逻辑(如写 checkpoint、提交 offset)log.Fatal() 或 os.Exit() 的兜底信号监听是异步的,main() 函数如果提前返回,进程就结束了,shutdown 流程根本没机会执行。必须让 main 阻塞住,直到 shutdown 完成。
return,或用 time.Sleep(1 * time.Hour) 这种硬编码等待sync.WaitGroup 或 chan struct{} 等待 shutdown 完成后再退出os.Exit(0),避免 defer 里有 panic 导致退出码异常最易忽略的一点:任何通过 log.Fatal() 触发的 panic 都会绕过 defer,导致 cleanup 逻辑不执行。所有关键日志建议用 log.Printf() + 显式 os.Exit()。