在kubernetes中实现go应用的优雅退出,核心做法是捕获sigterm信号并执行清理逻辑后调用os.exit(0),同时确保容器配置了合理的terminationgraceperiodseconds以等待清理完成。通过设置liveness和readiness探针,kubernetes会在发送sigterm前停止流量分发,而go程序内部需注册信号处理器来接管生命周期,避免被强制杀死导致数据丢失或连接中断。

signal.Notify如何注册SIGTERM处理函数
使用标准库signal包的Notify函数可以监听系统信号,当Kubernetes发送SIGTERM时,程序会进入指定的回调逻辑。开发者需要在main函数启动处创建通道并注册信号,随后在后台协程中阻塞等待该信号,收到信号后执行数据库连接关闭、缓存刷新等收尾工作,最后主动退出进程。

package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
sig := <-sigChan
log.Printf("Received signal %v, shutting down...", sig)
// 执行清理逻辑,如关闭DB连接
cleanup()
os.Exit(0)
}()
http.ListenAndServe(":8080", nil)
}
func cleanup() {
time.Sleep(2 * time.Second) // 模拟清理耗时
log.Println("Cleanup finished")
}
Kubernetes Pod的terminationGracePeriodSeconds应设为多少
Pod的terminationGracePeriodSeconds参数决定了Kubernetes等待Pod终止的最长时间,默认值为30秒。如果Go应用的清理逻辑超过这个时间,Kubernetes将发送SIGKILL强制杀死容器。因此,该值必须大于清理逻辑的最大耗时,通常建议设置为清理时间的1.5到2倍,以确保优雅退出能顺利完成。

# example-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: graceful-shutdown-example
spec:
terminationGracePeriodSeconds: 45 # 假设清理需要20秒,设为45秒留有余地
containers:
- name: app
image: my-go-app:latest
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
清理逻辑耗时超过terminationGracePeriodSeconds会发生什么
如果Go应用中的cleanup函数执行时间超过了Pod配置的terminationGracePeriodSeconds,Kubernetes不会无限期等待。在超时时刻,Kubelet会向容器内的主进程发送SIGKILL信号,该信号无法被Go程序的signal包捕获或忽略,导致进程立即终止。这会造成正在进行的请求被中断、未刷新的数据丢失以及可能的连接泄漏。因此,必须确保清理逻辑在超时前完成,或者适当增加超时时间。


















