Go应用容器化需暴露Prometheus指标并输出stdout日志:用promhttp.Handler挂载/metrics,禁用文件日志,设ENV GODEBUG=madvdontneed=1防OOM,探针与指标路径对齐。
Go 应用容器化后,监控不能只靠 docker stats 或宿主机指标——你需要从应用内部暴露可被 Prometheus 抓取的指标,并让日志能被统一采集(如通过 stdout 流式输出)。否则,指标断层、日志丢失、告警失灵是常态。
promhttp 暴露 Go 应用的 Prometheus 指标Go 生态最轻量、最标准的方式是用 prometheus/client_golang 提供的 promhttp.Handler()。它不侵入业务逻辑,只需在 HTTP 服务中挂载一个路由即可。
/metrics)注册到 HTTP mux 中,且路径不能带重定向或中间件拦截(否则 Prometheus 抓取会失败)Handler() 前加身份验证——Kubernetes Service 或 Ingress 层做访问控制更合理prometheus.NewCounterVec 等注册到全局 promet
heus.DefaultRegisterer,否则不会出现在 /metrics 输出里package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequests = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "status"},
)
)
func init() {
prometheus.MustRegister(httpRequests)
}
func handler(w http.ResponseWriter, r *http.Request) {
httpRequests.WithLabelValues(r.Method, "200").Inc()
w.WriteHeader(200)
w.Write([]byte("OK"))
}
func main() {
http.HandleFunc("/", handler)
http.Handle("/metrics", promhttp.Handler()) // 注意:直接挂载,不包装
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
os.Stdout,禁用文件写入Kubernetes 和大多数日志采集器(Fluentd、Filebeat、Loki 的 Promtail)只监听容器的 stdout 和 stderr。任何写本地文件(如 logrus.SetOutput(os.OpenFile(...)))的行为都会导致日志不可见。
log.SetOutput(os.Stdout) 或 logrus.SetOutput(os.Stdout) 替代文件句柄zerolog 或 logrus,并确保时间字段为 RFC3339 格式(time.RFC3339),方便 Loki / Grafana 解析\x1b[32m),某些采集器会截断或解析失败ENV GODEBUG=madvdontneed=1
Go 1.19+ 默认使用 madvise(MADV_DONTNEED) 释放内存,但在容器中常被 cgroup v1 或低版本内核误判为“内存泄漏”,触发 OOMKilled。加这个环境变量可回退到更保守的内存归还策略。
memory: 128Mi)、高并发短连接场景下高频出现FROM golang:1.22-alpine AS builder WORKDIR /app COPY . . RUN go build -o app . FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=builder /app/app . ENV GODEBUG=madvdontneed=1 EXPOSE 8080 CMD ["./app"]
Kubernetes 的 livenessProbe 和 readinessProbe 如果指向非指标路径(比如 /healthz),而 Prometheus 却只配置抓 /metrics,就会造成「Pod 一直存活,但指标长期中断」的假象。
/metrics 包含耗时操作(如实时查 Redis),否则 Prometheus 抓取超时会反复重试,反而压垮应用promhttp.HandlerFor 自定义 registry,请确认它没启用 EnableOpenMetrics(旧版客户端默认关,新版可能开),否则格式不兼容旧版 Prometheus最容易被忽略的是:指标暴露和日志输出看似独立,实则共享同一个约束——它们都依赖容器运行时对 stdout/stderr 和 HTTP 端口的透传能力。一旦在 K8s 中配错 securityContext(如禁用网络或重定向 stdout),两者会同时失效,但错误现象完全不同(一个是 503,一个是空日志流),排查时容易分头撞墙。