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

在Golang中实现容器健康检查逻辑,主要是通过暴露一个HTTP接口供Kubernetes或Docker等容器编排系统调用。这个接口用来反映服务当前是否正常运行。下面介绍如何构建一个简单但实用的健康检查机制。
最常见的方式是提供一个/healthz(或/health)端点,返回200状态码表示服务健康。
示例代码:
package main
<p>import (
"net/http"
"time"
)</p><p>func healthz(w http.ResponseWriter, r *http.Request) {
// 简单健康检查:只要服务能响应就是健康的
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}</p><p>func main() {
http.HandleFunc("/healthz", healthz)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!"))
})</p><pre class='brush:php;toolbar:false;'>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
<p>readinessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 5
periodSeconds: 5</p>如果服务依赖数据库、缓存或其他外部系统,健康检查应包含这些依赖的状态。
例如,检查数据库连接是否可用:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
<p>func dbHealthCheck(db *sql.DB) error {
return db.Ping()
}</p><p>func healthz(db <em>sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r </em>http.Request) {
if err := dbHealthCheck(db); err != nil {
http.Error(w, "Database unreachable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
}</p>使用方式:
db, _ := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
http.HandleFunc("/healthz", healthz(db))
建议分别提供两个接口,以便更精确控制容器行为。
示例:
func livenessHandler(w http.ResponseWriter, r *http.Request) {
// 只检查进程能否响应
w.Write([]byte("alive"))
}
<p>func readinessHandler(db <em>sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r </em>http.Request) {
if err := db.Ping(); err != nil {
http.Error(w, "Not ready", http.StatusServiceUnavailable)
return
}
w.Write([]byte("ready"))
}
}</p>这样可以让服务在数据库暂时不可用时停止接收请求(未就绪),但不重启(仍存活)。
避免健康检查因依赖阻塞而长时间无响应,可设置上下文超时:
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()
<pre class='brush:php;toolbar:false;'> 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语言免费学习笔记(深入)”;
基本上就这些。一个健壮的健康检查机制应该快速、轻量,并准确反映服务真实状态。不复杂但容易忽略。
以上就是如何在Golang中实现容器健康检查逻辑的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号