Fiber 的 app.Listen() 无法优雅停机,因其是阻塞调用且不暴露 *http.Server 实例,导致无法调用 Shutdown();必须手动创建 http.Server 并传入 app.Handler(),配合带超时的 context.Shutdown() 及资源关闭顺序才能实现优雅停机。

Fiber 的 app.Listen() 为什么不能直接优雅停机
Fiber 的 app.Listen() 是阻塞调用,内部封装了 http.Server.Serve(),不暴露 *http.Server 实例。一旦收到 SIGTERM 或 SIGINT,Go 运行时直接退出,defer 不执行,数据库连接、Redis 客户端、gRPC Server 等资源全被跳过关闭。
现象包括:日志突然中断、DB 连接池泄漏、K8s 报 Terminated: Error、pgx 提示 context canceled 却不是你主动 cancel 的。
根本原因是你没拿到 *http.Server,就无法调用 Shutdown() —— Fiber 没有像 Gin 那样提供 RunTLS 或 StartServer 的变体来返回 server 实例。
必须手动构造 *http.Server 并接管启动流程
绕过 app.Listen(),改用标准库的 http.Server 启动,才能控制 shutdown 生命周期。Fiber 的 app.Handler() 返回一个 http.Handler,可直接传给 http.Server。
关键步骤:
- 用
app.Handler()获取 handler,不要用app.Listen() - 显式创建
http.Server{Addr: ":8080", Handler: app.Handler()} - 在 goroutine 中调
srv.ListenAndServe(),避免阻塞 main - 保留
srv实例,用于后续Shutdown()
示例片段:
srv := &http.Server{
Addr: ":8080",
Handler: app.Handler(),
}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
srv.Shutdown() 必须带超时 context,且不能用 context.Background()
Shutdown() 本身不设超时,只做两件事:拒绝新连接 + 等所有 handler 返回。如果某个 handler 卡在没设 deadline 的 db.QueryContext()、redis.Client.Get() 或空 select{} 上,它会永远 hang 住。
错误写法:srv.Shutdown(context.Background()) → 进程卡死,K8s 在 terminationGracePeriodSeconds 后发 SIGKILL
正确写法(含超时与 cancel):
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("shutdown error: %v", err)
}
超时值建议:
- 比业务 P99 延迟高 5–10 秒
- 必须小于 K8s 的
terminationGracePeriodSeconds(例如后者是 30s,这里设 25s)
HTTP 之外的资源必须手动关,顺序不能错
srv.Shutdown() 只处理 HTTP 连接层。Fiber 应用里常见的额外资源包括:
-
pgxpool.Pool:调pool.Close(),但它不中断活跃事务——你的 handler 必须用pool.ExecContext(ctx, ...),否则Close()会等不到返回 -
redis.Client:调client.Close(),同样依赖 handler 内部使用client.GetContext(ctx, ...) - gRPC Server:用
grpcServer.GracefulStop()(不是Stop()),但注意它不等待流式 RPC 结束,需配合sync.WaitGroup记录活跃 stream - 自定义 goroutine(如定时任务、消息消费者):用
context.WithCancel()控制生命周期,并在 shutdown 前调cancel()
关闭顺序很重要:先让 HTTP 停收新请求(Shutdown()),再等 DB/Redis/gRPC 处理完最后一批请求,最后才真正 close 连接池或 stop gRPC。顺序反了,db.Query() 可能 panic “connection closed”。
最容易被忽略的是:所有 handler 内部必须把 shutdown context 透传下去,而不是硬编码 context.Background() —— 否则 Shutdown() 的超时对它们完全无效。


















