在Golang中实现容器健康检查需暴露/healthz接口,区分liveness与readiness探针,支持依赖检测与超时控制,确保服务状态准确反映。

在Golang中实现容器健康检查逻辑,主要是通过暴露一个HTTP接口供Kubernetes或Docker等容器编排系统调用。这个接口用来反映服务当前是否正常运行。下面介绍如何构建一个简单但实用的健康检查机制。
1. 实现基本的健康检查HTTP接口
最常见的方式是提供一个/healthz(或/health)端点,返回200状态码表示服务健康。
示例代码:
package mainimport ( "net/http" "time" )
func healthz(w http.ResponseWriter, r *http.Request) { // 简单健康检查:只要服务能响应就是健康的 w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) }
func main() { http.HandleFunc("/healthz", healthz) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World!")) })
server := &http.Server{ Addr: ":8080", ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, } server.ListenAndServe()}
立即学习“go语言免费学习笔记(深入)”;
将此服务部署到容器后,可在Kubernetes的Pod配置中添加liveness和readiness探针:
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
readinessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
2. 实现依赖项健康检查
如果服务依赖数据库、缓存或其他外部系统,健康检查应包含这些依赖的状态。
例如,检查数据库连接是否可用:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func dbHealthCheck(db *sql.DB) error {
return db.Ping()
}
func healthz(db sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r http.Request) {
if err := dbHealthCheck(db); err != nil {
http.Error(w, "Database unreachable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
}
使用方式:
db, _ := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
http.HandleFunc("/healthz", healthz(db))
3. 区分Liveness与Readiness检查
建议分别提供两个接口,以便更精确控制容器行为。
- Liveness:用于判断应用是否卡死,若失败则重启容器
- Readiness:用于判断是否准备好接收流量,失败则从负载均衡中剔除
示例:
func livenessHandler(w http.ResponseWriter, r *http.Request) {
// 只检查进程能否响应
w.Write([]byte("alive"))
}
func readinessHandler(db sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r http.Request) {
if err := db.Ping(); err != nil {
http.Error(w, "Not ready", http.StatusServiceUnavailable)
return
}
w.Write([]byte("ready"))
}
}
这样可以让服务在数据库暂时不可用时停止接收请求(未就绪),但不重启(仍存活)。
4. 添加检查超时保护
避免健康检查因依赖阻塞而长时间无响应,可设置上下文超时:
func readinessHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
done := make(chan error, 1)
go func() {
done <- db.PingContext(ctx)
}()
select {
case <-ctx.Done():
http.Error(w, "Timeout", http.StatusGatewayTimeout)
case err := <-done:
if err != nil {
http.Error(w, "DB unreachable", http.StatusServiceUnavailable)
return
}
w.Write([]byte("ready"))
}
}}
立即学习“go语言免费学习笔记(深入)”;
基本上就这些。一个健壮的健康检查机制应该快速、轻量,并准确反映服务真实状态。不复杂但容易忽略。










