如何优雅地关闭在 Kubernetes 上运行的 Go 服务

我有一个用 Go 编写的 API,它已经被 Docker 化并在 GKE 上的 Kubernetes 集群中运行。

目前,我的 API 服务器不处理任何关闭场景,例如 Pod 死亡或被故意关闭。

我应该期望捕获哪一组 UNIX 信号以正常关闭服务器以及什么情况会触发它们?例如,崩溃、K8s 关闭等。


翻翻过去那场雪
浏览 138回答 2
2回答

忽然笑

Kubernetes 发出一个SIGTERM信号。所以优雅的关机可能看起来像这样:package mainimport (&nbsp; &nbsp; "context"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "os"&nbsp; &nbsp; "os/signal"&nbsp; &nbsp; "syscall")func main() {&nbsp; &nbsp; var srv http.Server&nbsp; &nbsp; idleConnsClosed := make(chan struct{})&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; sigint := make(chan os.Signal, 1)&nbsp; &nbsp; &nbsp; &nbsp; // interrupt signal sent from terminal&nbsp; &nbsp; &nbsp; &nbsp; signal.Notify(sigint, os.Interrupt)&nbsp; &nbsp; &nbsp; &nbsp; // sigterm signal sent from kubernetes&nbsp; &nbsp; &nbsp; &nbsp; signal.Notify(sigint, syscall.SIGTERM)&nbsp; &nbsp; &nbsp; &nbsp; <-sigint&nbsp; &nbsp; &nbsp; &nbsp; // We received an interrupt signal, shut down.&nbsp; &nbsp; &nbsp; &nbsp; if err := srv.Shutdown(context.Background()); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Error from closing listeners, or context timeout:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("HTTP server Shutdown: %v", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; close(idleConnsClosed)&nbsp; &nbsp; }()&nbsp; &nbsp; if err := srv.ListenAndServe(); err != http.ErrServerClosed {&nbsp; &nbsp; &nbsp; &nbsp; // Error starting or closing listener:&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("HTTP server ListenAndServe: %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; <-idleConnsClosed}您还应该将 Liveness 和 Readiness 探测器添加到您的 Pod 中:livenessProbe:&nbsp; httpGet:&nbsp; &nbsp; path: /health&nbsp; &nbsp; port: 80readinessProbe:&nbsp; httpGet:&nbsp; &nbsp; path: /health&nbsp; &nbsp; port: 80

牛魔王的故事

当 Kubernetes 发送SIGTERM信号流量仍然可以路由到 pod 时,因为从端点集和SIGTERM信号中删除 pod 是异步的——如果 pod 在SIGTERM端点之后可能没有时间更新。 SIGTERM只是礼貌地要求开始收尾,但不要立即停止接受新的请求。您可以在<-sigint部署之后或添加到部署中后将睡眠添加到您的代码中lifecycle:       preStop:               exec:                        command: ["sh", "-c", "sleep 10"]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go