2026-11-11 12:57:24 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 12 章 日志:从 kubectl logs 到可检索 · Kubernetes 专题知识库< / title >
< meta name = "description" content = "本章从三个终端各自 kubectl logs 却拼不出一次下单失败讲起:先把 shop-api 的日志改成标准库 slog 的结构化 JSON, 再用 Helm 把 Loki、Grafana 与 Alloy 采集器装进 platform 命名空间,让日志第一次能按 trace_id 检索、按 app 标签统计,并讲清节点日志目录与轮转的关系。" >
< meta name = "keywords" content = "kubectl logs, Loki, Grafana Alloy, Helm, 结构化日志, trace_id, Kubernetes" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< a class = "brand" href = "index.html" >
< span class = "logo" > K8S< / span >
< div > Kubernetes 专题< small > 从第一个 Pod 到生产平台< / small > < / div >
< / a >
< div class = "crumbs" >
< a href = "index.html" > 总目录< / a >
< span class = "sep" > /< / span >
< b > 第 12 章< / b >
< / div >
< div class = "spacer" > < / div >
< button id = "tocToggle" type = "button" > ☰ 导航< / button >
< button id = "themeBtn" type = "button" > 深色< / button >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
2026-11-11 21:57:56 +08:00
< nav id = "chapters" > < div class = "toc-stage" > < b > S0< / b > < span class = "h" > 起步:环境与心智< / span > < / div > < a class = "toc-a" href = "00-why.html" > < i class = "cn" > 0< / i > 从一次线上事故理解 K8s< / a > < a class = "toc-a" href = "01-env.html" > < i class = "cn" > 1< / i > 装第一个集群: Windows 11 + WSL2 与 Linux 双轨< / a > < a class = "toc-a" href = "02-kubectl.html" > < i class = "cn" > 2< / i > kubectl 与集群解剖:把黑盒变成可观测对象< / a > < div class = "toc-stage" > < b > S1< / b > < span class = "h" > 跑起来:单服务最小闭环< / span > < / div > < a class = "toc-a" href = "03-pod.html" > < i class = "cn" > 3< / i > Pod: 最小调度单元< / a > < a class = "toc-a" href = "04-deployment.html" > < i class = "cn" > 4< / i > Deployment: 副本与滚动更新< / a > < a class = "toc-a" href = "05-service.html" > < i class = "cn" > 5< / i > Service 与集群 DNS< / a > < a class = "toc-a" href = "06-config.html" > < i class = "cn" > 6< / i > 配置与密钥: ConfigMap 与 Secret< / a > < a class = "toc-a" href = "07-probe.html" > < i class = "cn" > 7< / i > 探针与资源:让它活得像生产< / a > < div class = "toc-stage" > < b > S2< / b > < span class = "h" > 撑得住:状态、入口与多服务< / span > < / div > < a class = "toc-a" href = "08-storage.html" > < i class = "cn" > 8< / i > 存储:从 emptyDir 到 StatefulSet< / a > < a class = "toc-a" href = "09-ingress.html" > < i class = "cn" > 9< / i > 入口与网关: Ingress 与 Gateway API< / a > < a class = "toc-a" href = "10-job.html" > < i class = "cn" > 10< / i > Job 与 CronJob: 迁移与定时任务< / a > < a class = "toc-a" href = "11-multisvc.html" > < i class = "cn" > 11< / i > 多服务与网络策略< / a > < div class = "toc-stage" > < b > S3< / b > < span class = "h" > 看得见:可观测、发布与排障< / span > < / div > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 12< / i > 日志:从 kubectl logs 到可检索< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-12-1" > 12.1 本章在哪:从「能看」到「能查」< / a > < a class = "toc-a lv3" href = "#sec-12-2" > 12.2 学习目标< / a > < a class = "toc-a lv3" href = "#sec-12-3" > 12.3 场景:三个终端,一次失败的下单< / a > < a class = "toc-a lv3" href = "#sec-12-4" > 12.4 心智模型:一行日志的四次搬家< / a > < a class = "toc-a lv3" href = "#sec-12-5" > 12.5 概念与字段速查< / a > < a class = "toc-a lv3" href = "#sec-12-6" > 12.6 动手:把日志送进 Loki< / a > < a class = "toc-a lv3" href = "#sec-12-7" > 12.7 验收清单< / a > < a class = "toc-a lv3" href = "#sec-12-8" > 12.8 故障实验室< / a > < a class = "toc-a lv3" href = "#sec-12-9" > 12.9 生产对照< / a > < a class = "toc-a lv3" href = "#sec-12-10" > 12.10 清理< / a > < a class = "toc-a lv3" href = "#sec-12-11" > 12.11 小结与自测< / a > < a class = "toc-a lv3" href = "#sec-12-12" > 12.12 衔接:从「这一条日志」到「整体失败率」< / a > < a class = "toc-a lv3" href = "#sec-12-13" > 12.13 参考与验证版本< / a > < / div > < a class = "toc-a" href = "13-metrics.html" > < i class = "cn" > 13< / i > 指标、扩缩与告警< / a > < a class = "toc-a" href = "14-release.html" > < i class = "cn" > 14< / i > 发布策略:滚动、蓝绿、金丝雀< / a > < a class = "toc-a" href = "15-supply.html" > < i class = "cn" > 15< / i > 密钥与镜像供应链< / a > < a class = "toc-a" href = "16-debug.html" > < i class = "cn" > 16< / i > 故障诊断方法论:六类故障,一张诊断树< / a > < div class = "toc-stage" > < b > S4< / b > < span class = "h" > 上生产:集群、调度、安全、交付< / span > < / div > < a class = "toc-a" href = "17-kubeadm.html" > < i class = "cn" > 17< / i > 生产集群搭建: kubeadm HA< / a > < a class = "toc-a" href = "18-schedule.html" > < i class = "cn" > 18< / i > 节点、调度与容量< / a > < a class = "toc-a" href = "19-rbac.html" > < i class = "cn" > 19< / i > 安全基线: RBAC 与准入< / a > < a class = "toc-a" href = "20-gitops.html" > < i class = "cn" > 20< / i > GitOps: Helm/Kustomize + Argo CD< / a > < a class = "toc-a" href = "21-ci.html" > < i class = "cn" > 21< / i > CI/CD 流水线< / a > < a class = "toc-a" href = "22-backup.html" > < i class = "cn" > 22< / i > 备份、恢复与升级< / a > < div class = "toc-stage" > < b > S5< / b > < span class = "h" > 守得住:值班、成本与评审< / span > < / div > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 23< / i > 值班与事故响应< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 24< / i > 成本与容量< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 25< / i > 生产就绪评审与下一步< / span > < / nav >
2026-11-11 12:57:24 +08:00
< div class = "side-foot" > < a class = "btn" href = "index.html" > ← 总目录< / a > < / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< h2 id = "ch12" > < span class = "n" > 12< / span > 日志:从 kubectl logs 到可检索< / h2 >
< p class = "chapnav" >
< a href = "index.html" > Kubernetes 专题< / a >
< span > ·< / span >
< span > S3 看得见:可观测、发布与排障< / span >
< span > ·< / span >
< span > 第 < b class = "pos" > 12< / b > / 26 章< / span >
< / p >
< div class = "lead" >
< p > 这一章把「看日志」换成「查日志」:日志先变成结构化数据,再离开节点。< / p >
< p > 你动一个 Go 文件、三个 values 文件和几条 Helm 命令。< / p >
< p > 做完之后,一个请求 id 能在 Grafana 里定位到它那一行。< / p >
< / div >
< h3 id = "sec-12-1" > 12.1 本章在哪:从「能看」到「能查」< / h3 >
< p > 第 11 章结束时,< code > shop< / code > 里四个工作负载都在跑,日志只能一个个 Pod 去翻。本章只做两件事:把 < code > shop-api< / code > 的输出改成有固定字段的 JSON, 再把这些落在节点磁盘上的 JSON 收进一个能按标签查询的地方。只改应用不采集,你还得逐个 Pod 看;只采集不改格式,进了 Loki 也只是一团没法过滤的文本。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 位置< / th > < th > 内容< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 主线之前(第 11 章结束)< / td > < td > 四个工作负载可访问,日志只在节点上,用 < code > kubectl logs< / code > 逐个看< / td > < / tr >
< tr > < td > 主线之后(第 13 章开始)< / td > < td > 指标进 Prometheus, HPA 按 CPU 扩缩, 5xx 比例触发告警< / td > < / tr >
< tr > < td > 本章产物< / td > < td > < code > apps/shop-api/logging.go< / code > 、< code > platform/values/{loki,alloy,grafana}.yaml< / code > 、< code > platform< / code > 里三个 Helm release、一段验收脚本< / td > < / tr >
< tr > < td > 适用环境< / td > < td > kind 单集群, WSL2 与 Linux 命令一致,不需要额外机器< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-12-2" > 12.2 学习目标< / h3 >
< div class = "box note" >
< span class = "bt" > 学完你能< / span >
< ul >
< li > 让 < code > shop-api< / code > 每条请求输出一行 JSON, 字段是 < code > ts< / code > 、< code > level< / code > 、< code > msg< / code > 、< code > trace_id< / code > 、< code > path< / code > ,并说清每个字段给谁用。< / li >
< li > 指出容器 stdout 在节点上的确切位置,解释为什么挂 < code > hostPath< / code > 的 DaemonSet 能读到所有 Pod 的日志。< / li >
< li > 用一份 values 把 Loki 装成单机模式,再用 < code > upgrade< / code > 、< code > history< / code > 、< code > rollback< / code > 改坏再改回来。< / li >
< li > 在 Grafana 里按命名空间与 app 标签统计日志量,并按 < code > trace_id< / code > 定位到唯一那一行。< / li >
< li > 判断「日志没了」属于哪种:采集没挂对、被轮转覆盖、跟着 Pod 删了。< / li >
< / ul >
< / div >
< h3 id = "sec-12-3" > 12.3 场景:三个终端,一次失败的下单< / h3 >
< p > 周一上午,一个用户说下单失败,页面只留了一句「请稍后重试」。你和两位同事各开一个终端,都敲 < code > kubectl -n shop logs -f deploy/shop-api< / code > ,一次只绑一个副本,于是看到三份互不相干的输出。翻了几分钟,除了启动那行什么都没有,因为应用根本没为请求写过日志。你们退回去看网关和 < code > shop-web< / code > 的访问日志,从时间戳上猜哪条 500 对应这位用户。更糟的是有个副本在排查中途被滚动更新换掉,日志随目录消失。< / p >
< div class = "box danger" >
< span class = "bt" > 现象< / span >
< p > 三个副本各说各话,没有任何一条能把「用户的一次点击」和「某一行输出」连起来。< / p >
< pre data-lang = "text" data-name = "三个终端里的全部内容" > 2026-11-11T09:38:11Z shop-api v1.2.3 listening on :8080 mode=dev theme=dark
2026-11-11T09:38:14Z shop-api v1.2.3 listening on :8080 mode=dev theme=dark
2026-11-11T09:38:19Z shop-api v1.2.3 listening on :8080 mode=dev theme=dark< / pre >
< / div >
< h3 id = "sec-12-4" > 12.4 心智模型:一行日志的四次搬家< / h3 >
< p > 把日志想成一件转手的包裹,它搬四次家:进程写 stdout, 容器运行时追加到节点文件; kubelet 决定文件放哪、何时轮转;采集器读走、贴标签、推给 Loki; 最后你在 Grafana 里查。见图 1。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 330" role = "img" aria-label = "日志从容器 stdout 到 Grafana 的四段路径,以及 Pod 删除时日志消失的位置" >
< defs >
< marker id = "a12" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" >
< path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--muted)" > < / path >
< / marker >
< marker id = "a12d" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" >
< path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--danger)" > < / path >
< / marker >
< / defs >
< rect x = "14" y = "40" width = "150" height = "66" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "89" y = "66" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > 容器 stdout< / text >
< text x = "89" y = "86" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 进程写的一行< / text >
< rect x = "200" y = "40" width = "150" height = "66" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "275" y = "66" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > 节点磁盘< / text >
< text x = "275" y = "86" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > /var/log/pods/…/0.log< / text >
< rect x = "386" y = "40" width = "150" height = "66" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "461" y = "66" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > Alloy< / text >
< text x = "461" y = "86" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > DaemonSet, 只读挂载< / text >
< rect x = "572" y = "40" width = "134" height = "66" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "639" y = "66" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > Loki 单机< / text >
< text x = "639" y = "86" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > PVC 上的 chunks< / text >
< path d = "M166,73 L196,73" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12)" > < / path >
< path d = "M352,73 L382,73" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12)" > < / path >
< path d = "M538,73 L568,73" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12)" > < / path >
< rect x = "572" y = "168" width = "134" height = "62" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "639" y = "193" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > Grafana< / text >
< text x = "639" y = "212" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > LogQL 查询界面< / text >
< path d = "M639,108 L639,164" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12)" > < / path >
< rect x = "386" y = "168" width = "150" height = "62" rx = "8" style = "fill:var(--soft);stroke:var(--line)" > < / rect >
< text x = "461" y = "193" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > 你的浏览器< / text >
< text x = "461" y = "212" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > port-forward 3000:80< / text >
< path d = "M538,199 L568,199" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12)" > < / path >
< rect x = "14" y = "168" width = "336" height = "62" rx = "8" style = "fill:var(--card);stroke:var(--danger)" > < / rect >
< text x = "182" y = "193" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > Pod 删除 → kubelet 删掉整个目录< / text >
< text x = "182" y = "212" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 日志和 Pod 一起消失< / text >
< path d = "M275,108 L275,164" style = "stroke:var(--danger);fill:none;stroke-dasharray:5 4" marker-end = "url(#a12d)" > < / path >
< text x = "14" y = "272" style = "fill:var(--muted);font-size:12px" > 轮转上限:单文件 10Mi、每容器留 5 个,一个容器最多约 50Mi, 超出就从最旧的删< / text >
< text x = "14" y = "296" style = "fill:var(--muted);font-size:12px" > 采集器只读这一层文件,所以拿得到所有 Pod 的日志,也拿不到 Pod 删除后的日志< / text >
< / svg >
< div class = "figcap" > < b > 图 1 ·< / b > 一行日志要经过哪四段,以及它在哪一段丢< / div >
< / figure >
< p > 这张图解释了本章的选择。采集器是 DaemonSet, 因为文件在每个节点上。< code > --previous< / code > 救不了被删的 Pod, 因为它读的还是同一个目录。Loki 另存一份, 才能把「会被删掉的目录」变成能查的索引。类比: stdout 是投信口, 节点磁盘是那排信箱, kubelet 是每天清空信箱的保洁, Loki 是归档的档案室——删掉 Pod 等于把信箱拆走。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 常见误解< / th > < th > 实际发生了什么< / th > < / tr >
< / thead >
< tbody >
< tr > < td > 日志存在容器里,容器重启才丢< / td > < td > 日志在节点文件系统上; Pod 删除、节点重建、轮转覆盖都会丢,容器重启反而不丢(< code > --previous< / code > 能看到上一次)< / td > < / tr >
< tr > < td > < code > kubectl logs< / code > 能看到这个 Pod 的全部历史< / td > < td > 它只读当前容器的当前文件,以及上一次容器留下的那一份< / td > < / tr >
< tr > < td > 装上 Loki 就有日志了< / td > < td > Loki 只负责存;没有采集器把文件读走,它一直是空库,而且不会报错< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-12-5" > 12.5 概念与字段速查< / h3 >
< p > 下表左半边是 Loki 与采集器的开关,右半边是 kubelet 那侧的默认值。第二列写「默认值」,因为它决定你不写会得到什么。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 字段< / th > < th > 作用< / th > < th > 默认值< / th > < th > 本章取值与理由< / th > < / tr >
< / thead >
< tbody >
< tr > < td > < code > deploymentMode< / code > < / td > < td > Loki 的部署形态< / td > < td > < code > Monolithic< / code > < / td > < td > 保持单机;老文档里的 < code > SingleBinary< / code > 是它的旧名< / td > < / tr >
< tr > < td > < code > singleBinary.replicas< / code > < / td > < td > 单机模式的副本数< / td > < td > < code > 0< / code > < / td > < td > 必须显式写 1, 否则装完没有 Pod< / td > < / tr >
< tr > < td > < code > loki.auth_enabled< / code > < / td > < td > 是否要求 < code > X-Scope-OrgID< / code > < / td > < td > < code > true< / code > < / td > < td > 学习环境关掉,少一层租户头< / td > < / tr >
< tr > < td > < code > loki.commonConfig.replication_factor< / code > < / td > < td > 每份日志写几个副本< / td > < td > < code > 3< / code > < / td > < td > 单机写 1, 否则一个实例无法满足< / td > < / tr >
< tr > < td > < code > loki.storage.type< / code > < / td > < td > chunks 存在哪< / td > < td > < code > s3< / code > < / td > < td > 改 < code > filesystem< / code > ,用 PVC 代替对象存储< / td > < / tr >
< tr > < td > < code > loki.schemaConfig< / code > < / td > < td > 索引的 schema 与周期< / td > < td > < code > {}< / code > (空会安装失败)< / td > < td > 写死 tsdb + v13, 之后不要再改< / td > < / tr >
< tr > < td > < code > singleBinary.persistence.size< / code > < / td > < td > 数据盘大小< / td > < td > < code > 10Gi< / code > < / td > < td > 保持 10Gi, kind 的 local-path 够用< / td > < / tr >
< tr > < td > < code > alloy.mounts.varlog< / code > < / td > < td > 是否把节点 < code > /var/log< / code > 挂进采集器< / td > < td > < code > false< / code > < / td > < td > 必须 true, 这是整条链路的前提< / td > < / tr >
< tr > < td > < code > alloy.resources< / code > < / td > < td > 采集器的 requests/limits< / td > < td > < code > {}< / code > < / td > < td > 显式给 128Mi/256Mi, 见故障 3< / td > < / tr >
< tr > < td > < code > admin.existingSecret< / code > < / td > < td > Grafana 管理员密码从哪来< / td > < td > < code > ""< / code > (用 values 明文)< / td > < td > 指向自建 Secret, 不把密码写进文件< / td > < / tr >
< tr > < td > < code > containerLogMaxSize< / code > < / td > < td > 单个日志文件的轮转阈值< / td > < td > < code > 10Mi< / code > < / td > < td > 不动,这是节点磁盘的第一道闸< / td > < / tr >
< tr > < td > < code > containerLogMaxFiles< / code > < / td > < td > 每个容器保留几个文件< / td > < td > < code > 5< / code > < / td > < td > 不动,调大等于多占节点盘< / td > < / tr >
< tr > < td > < code > podLogsDir< / code > < / td > < td > 节点上日志文件的根目录< / td > < td > < code > /var/log/pods/< / code > < / td > < td > 不动, Alloy 的 glob 照这个路径写< / td > < / tr >
< / tbody >
< / table >
< / div >
< p class = "take" > 日志的持久化边界在节点上,不在容器里。< / p >
< p > 不装 MinIO 是因为单机只有一份数据、多副本用不上: kind 的 < code > local-path< / code > 已能提供 PVC( 第 8 章 < a href = "08-storage.html" > 存储< / a > 讲过回收策略)。代价是 < code > filesystem< / code > 下不能扩多副本,也不能跨节点。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点:改了 log_level, 日志级别没变< / span >
< p > < b > 现象< / b > : < code > log_level< / code > 已经从 < code > info< / code > 改成 < code > debug< / code > , Pod 里也确认新值挂进去了,日志里还是没有 debug 行。< / p >
< p > < b > 原因< / b > :第 6 章去掉了 < code > LOG_LEVEL< / code > 这个 env, 级别只能来自 < code > /etc/shop/config.yaml< / code > ; < code > newLogger()< / code > 只在进程启动时读一次。< / p >
< p > < b > 怎么验证< / b > : < code > kubectl -n shop exec deploy/shop-api -- cat /etc/shop/config.yaml< / code > 看到 < code > debug< / code > ,再 < code > kubectl -n shop rollout restart deploy/shop-api< / code > ,新 Pod 起来后才有 debug 行。< / p >
< / div >
< h3 id = "sec-12-6" > 12.6 动手:把日志送进 Loki< / h3 >
< p > 八个步骤:前两步动应用,中间三步动集群,最后三步验证与练习回滚。下表是本章用到的 Helm 动作。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 命令< / th > < th > 做什么< / th > < th > 本章出现在< / th > < / tr >
< / thead >
< tbody >
< tr > < td > < code > helm repo add< / code > < / td > < td > 把 chart 仓库登记成本地别名< / td > < td > Step 3< / td > < / tr >
< tr > < td > < code > helm install -f< / code > < / td > < td > 按 values 文件首次安装一个 release< / td > < td > Step 4、Step 5< / td > < / tr >
< tr > < td > < code > helm upgrade< / code > < / td > < td > 用新 values 改一个已存在的 release< / td > < td > Step 8< / td > < / tr >
< tr > < td > < code > helm history< / code > < / td > < td > 看这个 release 的所有 revision< / td > < td > Step 8、故障排查< / td > < / tr >
< tr > < td > < code > helm rollback< / code > < / td > < td > 回到某个 revision, 历史里新增一条而不是删掉< / td > < td > Step 8< / td > < / tr >
< tr > < td > < code > helm uninstall< / code > < / td > < td > 删掉 release, PVC 与 Secret 不归它管< / td > < td > 12.10< / td > < / tr >
< / tbody >
< / table >
< / div >
< h4 > Step 1 · 先确认上一章的现场还在< / h4 >
< p > < span class = "tag" > 意图< / span > 确认起点没被前面的实验弄坏,尤其副本数。< / p >
< pre data-lang = "bash" data-name = "校验起点" > # env: all
kubectl -n shop get deploy,sts
kubectl -n shop get pods< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
NAME READY UP-TO-DATE AVAILABLE AGE
shop-api 3/3 3 3 6d
shop-web 2/2 2 2 6d
shop-worker 1/1 1 1 6d
NAME READY AGE
postgres 1/1 6d
NAME READY STATUS RESTARTS AGE
shop-api-6f7c9d8b4d-2xk4l 1/1 Running 0 6d
shop-api-6f7c9d8b4d-9v7bp 1/1 Running 0 6d
shop-api-6f7c9d8b4d-tc4wm 1/1 Running 0 6d
shop-web-6c8f9d7b5c-4m2qp 1/1 Running 0 6d
shop-web-6c8f9d7b5c-r7ktn 1/1 Running 0 6d
shop-worker-6b9c4f7d8-x2m4q 1/1 Running 0 6d
postgres-0 1/1 Running 0 6d< / pre >
< p > < b > 不一致怎么办< / b > : Pod 不在 Running 先回第 11 章看网络策略;命名空间不存在说明集群被重建过,从第 3 章重跑 < code > make up< / code > 。< / p >
< h4 > Step 2 · 把 shop-api 的日志改成 JSON< / h4 >
< p > < span class = "tag" > 意图< / span > 一条请求变成一行 JSON, 字段固定; 级别仍只从挂进来的 < code > config.yaml< / code > 读。< / p >
< pre data-lang = "go" data-name = "apps/shop-api/logging.go" > // file: apps/shop-api/logging.go
package main
import (
"crypto/rand"
"encoding/hex"
"log/slog"
"net/http"
"os"
"strings"
)
// newLogger 固定输出五个字段: ts、level、msg、trace_id、path
func newLogger() *slog.Logger {
level := slog.LevelInfo
if raw, err := os.ReadFile("/etc/shop/config.yaml"); err == nil {
for _, line := range strings.Split(string(raw), "\n") {
line = strings.TrimSpace(line)
if after, ok := strings.CutPrefix(line, "log_level:"); ok {
_ = level.UnmarshalText([]byte(strings.TrimSpace(after)))
}
}
}
h := slog.NewJSONHandler(os.Stdout, & slog.HandlerOptions{
Level: level,
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
a.Key = "ts"
}
return a
},
})
return slog.New(h)
}
// withTrace 给每个没有 id 的请求发一个,写日志也回写给调用方
func withTrace(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Trace-Id")
if id == "" {
b := make([]byte, 8)
_, _ = rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Trace-Id", id)
log.Info("request", "trace_id", id, "path", r.URL.Path)
next.ServeHTTP(w, r)
})
}< / pre >
< p > 再改 < code > main.go< / code > 两处:< code > http.ListenAndServe(":8080", mux)< / code > 换成 < code > withTrace(logger, mux)< / code > ,两处 < code > log.Printf< / code > 换成 < code > logger.Info< / code > 。漏一处就混进一行非 JSON 文本。< / p >
< pre data-lang = "bash" data-name = "构建、载入、滚动更新" > # env: all
cd ~/work/aurora-shop
docker build -t registry.local/aurora/shop-api:v1.3.0 apps/shop-api
kind load docker-image registry.local/aurora/shop-api:v1.3.0 --name aurora
kubectl -n shop set image deploy/shop-api shop-api=registry.local/aurora/shop-api:v1.3.0
kubectl -n shop rollout status deploy/shop-api --timeout=90s< / pre >
< pre data-lang = "text" data-name = "预期输出:一条请求一行 JSON" > # 预期输出
{"ts":"2026-11-11T09:52:10.412Z","level":"INFO","msg":"request","trace_id":"9f1c2ab34d5e6f70","path":"/"}
{"ts":"2026-11-11T09:52:11.008Z","level":"INFO","msg":"request","trace_id":"1b77ce40a9d2f315","path":"/healthz"}< / pre >
< p > < b > 不一致怎么办< / b > :输出是 < code > {"time":"…"}< / code > 说明 < code > ReplaceAttr< / code > 没接上;还是 < code > 2026/11/11 …< / code > 就用 < code > grep -rn "log.Printf" apps/shop-api< / code > 找。< / p >
< h4 > Step 3 · 加两个 Helm 仓库< / h4 >
< p > < span class = "tag" > 意图< / span > 固定来源: Loki 与 Grafana 在社区仓库, Alloy 在 grafana 仓库。< / p >
< pre data-lang = "bash" data-name = "添加仓库" > # env: all
helm repo add grafana-community https://grafana-community.github.io/helm-charts
helm repo add grafana https://grafana.github.io/helm-charts
helm repo update
helm search repo grafana-community/loki --versions | head -3< / pre >
< p > 两条 < code > repo add< / code > 各回一行 < code > has been added to your repositories< / code > ,最后一条首行是 < code > grafana-community/loki< / code > 配 < code > 21.2.0< / code > 与 < code > 3.7.9< / code > 。< / p >
< p > < b > 不一致怎么办< / b > : < code > helm: command not found< / code > 就装 Helm 并重开终端;< code > search< / code > 空结果多半是 < code > repo update< / code > 没跑成。< / p >
< h4 > Step 4 · 装 Loki: 单机加文件系统< / h4 >
< p > < span class = "tag" > 意图< / span > 一份 values 改三个默认值:副本 0 改 1、s3 改 filesystem、桶改 PVC。< / p >
< pre data-lang = "yaml" data-name = "platform/values/loki.yaml" > # file: platform/values/loki.yaml
deploymentMode: Monolithic
fullnameOverride: loki
loki:
auth_enabled: false
commonConfig:
replication_factor: 1
storage:
type: filesystem
schemaConfig:
configs:
- from: "2024-04-01"
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
singleBinary:
replicas: 1
persistence:
enabled: true
size: 10Gi
chunksCache:
enabled: false
resultsCache:
enabled: false
gateway:
enabled: false
lokiCanary:
enabled: false
test:
enabled: false< / pre >
< pre data-lang = "bash" data-name = "安装 Loki 并检查 PVC" > # env: all
cd ~/work/aurora-shop
helm install loki grafana-community/loki \
-n platform \
--version 21.2.0 \
-f platform/values/loki.yaml \
--wait --timeout 6m
kubectl -n platform get sts,pods,pvc< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
NAME READY AGE
loki 1/1 96s
NAME READY STATUS RESTARTS AGE
loki-0 1/1 Running 0 96s
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
storage-loki-0 Bound pvc-3f2b… 10Gi RWO standard 96s< / pre >
< p > < b > 不一致怎么办< / b > :报 < code > schema_config< / code > 缺失是少了 < code > configs< / code > ;报 < code > more than 1 Monolithic replica< / code > 是 < code > replicas< / code > 不是 1; PVC Pending 看默认 StorageClass。< / p >
< h4 > Step 5 · 装 Alloy 与 Grafana, 把数据源接上< / h4 >
< p > < span class = "tag" > 意图< / span > 采集器读节点文件, Grafana 只当查询前端。< / p >
< pre data-lang = "yaml" data-name = "platform/values/alloy.yaml 与 platform/values/grafana.yaml" > # file: platform/values/alloy.yaml
alloy:
mounts:
varlog: true
resources:
requests:
cpu: 50m
memory: 128Mi
limits:
memory: 256Mi
configMap:
content: |-
discovery.kubernetes "pods" {
role = "pod"
namespaces {
names = ["shop"]
}
}
discovery.relabel "pods" {
targets = discovery.kubernetes.pods.targets
rule {
source_labels = ["__meta_kubernetes_pod_uid", "__meta_kubernetes_pod_container_name"]
separator = "/"
regex = "(.+)"
replacement = "/var/log/pods/*$1/*.log"
target_label = "__path__"
}
rule {
source_labels = ["__meta_kubernetes_namespace"]
target_label = "namespace"
}
rule {
source_labels = ["__meta_kubernetes_pod_name"]
target_label = "pod"
}
rule {
source_labels = ["__meta_kubernetes_pod_container_name"]
target_label = "container"
}
rule {
source_labels = ["__meta_kubernetes_pod_label_app_kubernetes_io_name"]
target_label = "app"
}
}
loki.source.file "pods" {
targets = discovery.relabel.pods.output
forward_to = [loki.write.default.receiver]
file_match {
enabled = true
}
}
loki.write "default" {
endpoint {
url = "http://loki.platform.svc.cluster.local:3100/loki/api/v1/push"
}
}
# file: platform/values/grafana.yaml
admin:
existingSecret: grafana-admin
datasources:
datasources.yaml:
apiVersion: 1
datasources:
- name: Loki
type: loki
uid: loki
url: http://loki.platform.svc.cluster.local:3100
access: proxy
isDefault: true< / pre >
< pre data-lang = "bash" data-name = "建密码、装采集器与界面" > # env: all
cd ~/work/aurora-shop
kubectl -n platform create secret generic grafana-admin \
--from-literal=admin-user=admin \
--from-literal=admin-password="$(openssl rand -base64 18)"
helm install alloy grafana/alloy \
-n platform --version 1.15.0 -f platform/values/alloy.yaml
helm install grafana grafana-community/grafana \
-n platform --version 14.4.1 -f platform/values/grafana.yaml \
--wait --timeout 5m
kubectl -n platform get ds alloy< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
secret/grafana-admin created
NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE AGE
alloy 2 2 2 2 2 48s< / pre >
< p > < b > 不一致怎么办< / b > : Alloy 报 < code > CreateContainerConfigError< / code > 多是语法错,< code > logs ds/alloy< / code > 第一行给行号;报 < code > secret … not found< / code > 是 Secret 建错命名空间。< / p >
< h4 > Step 6 · 负向验证: Pod 删了,日志就没了< / h4 >
< p > < span class = "tag" > 意图< / span > 亲手确认一次,不凭记忆。< / p >
< pre data-lang = "bash" data-name = "删一个副本,再回来找它的日志" > # env: all
POD=$(kubectl -n shop get pods -l app.kubernetes.io/name=shop-api -o name | head -1)
kubectl -n shop logs "$POD" --tail=1
kubectl -n shop delete "$POD"
kubectl -n shop logs "$POD" --previous< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
{"ts":"2026-11-11T09:58:31.004Z","level":"INFO","msg":"request","trace_id":"c40a1f9b2e7d8831","path":"/"}
pod "shop-api-6b7f9c8d54-2xk9p" deleted
Error from server (NotFound): pods "shop-api-6b7f9c8d54-2xk9p" not found< / pre >
< p > < b > 不一致怎么办< / b > : < code > --previous< / code > 真出了日志,说明那是容器重启不是 Pod 删除——重启能救,删除不能。< / p >
< h4 > Step 7 · 用 trace_id 把那一次请求捞出来< / h4 >
< p > < span class = "tag" > 意图< / span > 走完端到端:发 id、写一行、id 回手、再查回来。< / p >
< pre data-lang = "bash" data-name = "两个终端:一个开 Grafana, 一个发请求" > # env: all
kubectl -n platform port-forward svc/grafana 3000:80
# 另一个终端
kubectl -n shop port-forward svc/shop-api 8080:8080
curl -s -D - -o /dev/null http://127.0.0.1:8080/< / pre >
< pre data-lang = "text" data-name = "预期输出:响应头,以及 Explore 里的查询" > # 预期输出
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
X-Trace-Id: c40a1f9b2e7d8831
Date: Wed, 11 Nov 2026 10:02:14 GMT
# 把 id 抄进 Grafana Explore 的 Loki 查询
{namespace="shop", app="shop-api"} | json | trace_id="c40a1f9b2e7d8831"< / pre >
< p > 见图 2: 三跳里只有最后一跳记了 id, nginx 只是转发——这是请求级 id, 不是 OpenTelemetry 那种跨进程追踪。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 250" role = "img" aria-label = "trace_id 只在 shop-api 这一段生成并被记录" >
< defs >
< marker id = "a12t" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" >
< path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--muted)" > < / path >
< / marker >
< marker id = "a12b" markerWidth = "9" markerHeight = "9" refX = "8" refY = "4.5" orient = "auto" >
< path d = "M0,0 L9,4.5 L0,9 z" style = "fill:var(--brand)" > < / path >
< / marker >
< / defs >
< rect x = "14" y = "52" width = "120" height = "72" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "74" y = "80" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > 浏览器< / text >
< text x = "74" y = "100" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 没有 id< / text >
< rect x = "184" y = "52" width = "120" height = "72" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "244" y = "80" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > 网关 shop-gw< / text >
< text x = "244" y = "100" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 只转发< / text >
< rect x = "354" y = "52" width = "120" height = "72" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "414" y = "80" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > shop-web< / text >
< text x = "414" y = "100" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 只转发< / text >
< rect x = "524" y = "52" width = "180" height = "72" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "614" y = "76" text-anchor = "middle" style = "fill:var(--ink);font-size:13px" > shop-api< / text >
< text x = "614" y = "96" text-anchor = "middle" style = "fill:var(--muted);font-size:11px" > 生成 id、写日志、回写头< / text >
< path d = "M136,88 L180,88" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12t)" > < / path >
< path d = "M306,88 L350,88" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12t)" > < / path >
< path d = "M476,88 L520,88" style = "stroke:var(--muted);fill:none" marker-end = "url(#a12t)" > < / path >
< path d = "M614,126 L614,160 L74,160 L74,128" style = "stroke:var(--brand);fill:none;stroke-dasharray:5 4" marker-end = "url(#a12b)" > < / path >
< text x = "344" y = "152" text-anchor = "middle" style = "fill:var(--brand);font-size:12px" > 响应头 X-Trace-Id 原路返回< / text >
< text x = "14" y = "200" style = "fill:var(--muted);font-size:12px" > 这条链上只有 shop-api 记录了 trace_id: 它不是 OpenTelemetry, 也不跨进程传播< / text >
< text x = "14" y = "222" style = "fill:var(--muted);font-size:12px" > 要跨服务追踪,得换一套 SDK 并在每一跳注入 header, 那是另一个话题< / text >
< / svg >
< div class = "figcap" > < b > 图 2 ·< / b > id 在哪一段产生、在哪一段被记下来< / div >
< / figure >
< p > < b > 不一致怎么办< / b > :没有 < code > X-Trace-Id< / code > 是 < code > withTrace< / code > 没包住 mux, 或镜像没换成功; 查不到先看时间范围, 再确认 < code > app< / code > 来自 Pod 标签。< / p >
< h4 > Step 8 · 改一个值,走一遍 upgrade、history、rollback< / h4 >
< p > < span class = "tag" > 意图< / span > 把 < code > upgrade< / code > 、< code > history< / code > 、< code > rollback< / code > 练到不看文档。< / p >
< pre data-lang = "bash" data-name = "升级、看历史、回滚" > # env: all
cd ~/work/aurora-shop
helm upgrade grafana grafana-community/grafana \
-n platform --version 14.4.1 -f platform/values/grafana.yaml \
--set grafana.ini.analytics.check_for_updates=false
helm history grafana -n platform
helm rollback grafana 1 -n platform
kubectl -n platform rollout status deploy/grafana< / pre >
< p > < code > upgrade< / code > 后 history 两行: revision 1 < code > superseded< / code > 、2 < code > deployed< / code > 。回滚到 1 是新增 revision 3——历史只增不改。< / p >
< p > < b > 不一致怎么办< / b > :报 < code > another operation (install/upgrade/rollback) is in progress< / code > 就等前一个结束;回滚后看着没变,用 < code > helm get values grafana -n platform --revision 2< / code > 核对那一版。< / p >
< h3 id = "sec-12-7" > 12.7 验收清单< / h3 >
< p > 六条按顺序做,每条都能独立判断真假。最后一条是反向验证:证明「不再有非 JSON 的行」。< / p >
< ol class = "steps" >
< li > < code > kubectl -n platform get sts loki< / code > 的 READY 是 < code > 1/1< / code > ,日志里没有 < code > level=error< / code > 。< / li >
< li > < code > kubectl -n platform get ds alloy< / code > 的 READY 等于 DESIRED, 本章是 2。< / li >
< li > Explore 里 < code > {namespace="shop"}< / code > 有结果。< / li >
< li > < code > sum by (app) (count_over_time({namespace="shop"}[5m]))< / code > 覆盖四个 app。< / li >
< li > 响应头的 id 填进 < code > | json | trace_id="…"< / code > ,只命中一行。< / li >
< li > 反向:< code > kubectl -n shop logs deploy/shop-api --tail=50 | grep -v '^{'< / code > 输出为空。< / li >
< / ol >
< p > 把前五条写进脚本,跑完打印五个 < code > [ok]< / code > ,就是本章的 < code > verify-ch12< / code > ; Makefile 里的目标只是给它包一层,第六条反向检查在本地跑。< / p >
< pre data-lang = "bash" data-name = "验收脚本:五条断言" > # env: all
set -euo pipefail
kubectl -n platform rollout status sts/loki --timeout=120s >/dev/null & & echo "[ok] loki-0 就绪"
kubectl -n platform rollout status ds/alloy --timeout=120s >/dev/null & & echo "[ok] alloy 每节点一份就绪"
kubectl -n platform port-forward svc/loki 3100:3100 >/dev/null 2>& 1 &
PF=$!; sleep 3
curl -sf http://127.0.0.1:3100/ready | grep -q ready & & echo "[ok] loki /ready 返回 ready"
APPS=$(curl -sG http://127.0.0.1:3100/loki/api/v1/query \
--data-urlencode 'query=count(count_over_time({namespace="shop"}[5m])) by (app)' \
| grep -o '"app":"[a-z-]*"' | sort -u | wc -l)
[ "$APPS" -ge 4 ] & & echo "[ok] 5 分钟内 $APPS 个 app 在写日志"
curl -sG http://127.0.0.1:3100/loki/api/v1/query_range \
--data-urlencode 'query={namespace="shop", app="shop-api"} | json | trace_id != ""' \
--data-urlencode 'limit=1' | grep -q '"path"' & & echo "[ok] trace_id 查询命中带 path 的 JSON 行"
kill $PF< / pre >
< div class = "box warn" >
< span class = "bt" > 易错点:日志里明明有,< code > | json< / code > 就是查不到< / span >
< p > < b > 现象< / b > : < code > |= "c40a1f9b"< / code > 能搜到,换成 < code > | json | trace_id="c40a1f9b2e7d8831"< / code > 就没有结果。< / p >
< p > < b > 原因< / b > : < code > | json< / code > 只解析能解析的行,混进来的 < code > log.Printf< / code > 文本行会让解析报错,而报错行被当成没有该字段。< / p >
< p > < b > 怎么验证< / b > :把查询换成 < code > {namespace="shop", app="shop-api"} | json | __error__ != ""< / code > ,能看到的行就是元凶;回到 Step 2 把那处 < code > log.Printf< / code > 改掉。< / p >
< / div >
< h3 id = "sec-12-8" > 12.8 故障实验室< / h3 >
< p > 三个故障都真实发生过:第一个让你以为 Loki 坏了,第二个让节点开始驱逐 Pod, 第三个让采集器自己成为被驱逐的对象。< / p >
< div class = "box danger" >
< span class = "bt" > 故障 1: Loki 起来了, Grafana 里一条日志都没有< / span >
< p > < b > 注入< / b > :把 < code > alloy.mounts.varlog< / code > 改回 < code > false< / code > 再 upgrade, 等两分钟。< / p >
< p > < b > 症状< / b > : Grafana 里 < code > {namespace="shop"}< / code > 返回 < code > No data< / code > ; < code > kubectl -n platform logs ds/alloy< / code > 隔一会儿一行 < code > msg="no files matched"< / code > ,而 Pod 一直是 Running。< / p >
< p > < b > 诊断< / b > : < code > exec ds/alloy -- ls /var/log/pods< / code > 报 < code > No such file or directory< / code > ; < code > get ds alloy -o jsonpath='{.spec.template.spec.volumes}'< / code > 里没有 < code > /var/log< / code > 的 < code > hostPath< / code > 。< / p >
< p > < b > 根因< / b > : < code > alloy.mounts.varlog< / code > 默认 < code > false< / code > ,容器里没有 < code > /var/log/pods< / code > , glob 匹配不到任何文件。采集器不把它当错误,只是持续重试,链路看着「通」却永远没数据。< / p >
< p > < b > 修复< / b > :改回 < code > true< / code > 再 upgrade, 确认新 Pod 里 < code > ls /var/log/pods< / code > 能看到 < code > shop_…< / code > 开头的目录。< / p >
< p > < b > 预防< / b > :把「容器里看得见 < code > /var/log/pods< / code > 」写进验收:先证明看得见源数据,再证明推得出去。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 2: 日志把节点磁盘写满, Pod 被驱逐< / span >
< p > < b > 注入< / b > : < code > kubectl -n shop exec deploy/shop-api -- dd if=/dev/zero of=/tmp/big.log bs=1M count=6000< / code > 。容器可写层也算 nodefs, 这就是在它上面堆 6GiB。< / p >
< p > < b > 症状< / b > : < code > get pods< / code > 里出现 < code > Evicted< / code > , < code > describe node< / code > 的 < code > DiskPressure< / code > 变 < code > True< / code > ,事件写 < code > The node was low on resource: nodefs.< / code > < / p >
< p > < b > 诊断< / b > : < code > kubectl -n shop get events --field-selector reason=Evicted< / code > 能看到被驱逐的 Pod 与原因;< code > kubectl -n shop exec deploy/shop-api -- df -h /tmp< / code > 看是不是它写的。< / p >
< p > < b > 根因< / b > : kubelet 只轮转 stdout 那个文件( 10Mi × 5) , < code > emptyDir< / code > 和容器可写层不在轮转范围内。nodefs 可用低于 10% 触发硬驱逐, kubelet 按 QoS 挑最软的杀。< / p >
< p > < b > 修复< / b > :删掉大文件释放空间,< code > kubectl -n shop rollout restart deploy/shop-api< / code > ; < code > DiskPressure< / code > 变回 < code > False< / code > 后被驱逐的 Pod 才会重新调度。< / p >
< p > < b > 预防< / b > :应用日志只写 stdout 交给 kubelet; 必须落盘的挂 < code > emptyDir< / code > 时写 < code > sizeLimit< / code > ;节点盘与数据盘分开并监控 nodefs( 第 13 章)。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 3: 采集器自己 OOMKilled< / span >
< p > < b > 注入< / b > : < code > helm upgrade alloy grafana/alloy -n platform -f platform/values/alloy.yaml --set alloy.resources.limits.memory=64Mi< / code > ,再让日志量涨上来。< / p >
< p > < b > 症状< / b > : RESTARTS 持续增长, STATUS 在 < code > Running< / code > 与 < code > CrashLoopBackOff< / code > 之间来回,日志某一刻直接断掉。< / p >
< p > < b > 诊断< / b > : < code > kubectl -n platform get pods -l app.kubernetes.io/name=alloy -o jsonpath='{.items[0].status.containerStatuses[0].lastState}'< / code > 给出 < code > reason: OOMKilled, exitCode: 137< / code > 。< / p >
< p > < b > 根因< / b > : < code > alloy.resources< / code > 默认 < code > {}< / code > , chart 不给任何 requests/limits。加了 64Mi 的 limit, 它就是内核的硬边界: Alloy 同时 tail 本节点所有容器、按 stream 维护缓冲,堆随活跃 stream 数增长,超了就杀。< / p >
< p > < b > 修复< / b > : limit 提到 512Mi、requests 给 128Mi 再 upgrade; 内存仍涨就降 < code > loki.write< / code > 的批大小,别用调大 limit 掩盖泄漏。< / p >
< p > < b > 预防< / b > :采集器和业务 Pod 一样要有 requests/limits; 按节点日志量估内存, 别照抄 64Mi。< / p >
< / div >
< h3 id = "sec-12-9" > 12.9 生产对照< / h3 >
< p > 本章每一处简化在生产上都有代价,下表按「教程里、生产上、为什么、迁移动作」对照。< / p >
< div class = "tablewrap" >
< table >
< thead >
< tr > < th > 维度< / th > < th > 教程里( kind) < / th > < th > 生产上< / th > < th > 为什么< / th > < th > 迁移动作< / th > < / tr >
< / thead >
< tbody >
< tr > < td > Loki 形态< / td > < td > Monolithic, 1 副本, filesystem< / td > < td > Microservices( 读写分离) 或 SimpleScalable, 对象存储< / td > < td > 单进程的读写抢同一份本地盘 IO; 对象存储让读写各自扩< / td > < td > 换 values, 加 bucket 与 < code > X-Scope-OrgID< / code > < / td > < / tr >
< tr > < td > 采集器< / td > < td > Alloy DaemonSet 直接推 Loki< / td > < td > DaemonSet 推到本集群网关,再由中心集群聚合< / td > < td > 每节点直连远端会让出口流量和重试不可控,中间一层能缓冲、能限流< / td > < td > 把 < code > loki.write< / code > 的 URL 指向网关< / td > < / tr >
< tr > < td > 成本< / td > < td > 全量保留, 10Gi 盘< / td > < td > 热 7 天、冷 30– 90 天,高基数日志采样< / td > < td > 成本约等于写入量 × 保留天数 × 副本数,压任何一个都比换存储便宜< / td > < td > 配 retention、按 namespace 采样< / td > < / tr >
< tr > < td > PII 与权限< / td > < td > 谁 port-forward 谁都能看< / td > < td > 采集端脱敏, Loki 多租户, Grafana 按团队分权限< / td > < td > 日志里最容易漏 token、手机号; 进了库就很难逐条删< / td > < td > < code > auth_enabled: true< / code > 、脱敏 pipeline< / td > < / tr >
< tr > < td > 多集群< / td > < td > 一个集群,一个 Loki< / td > < td > 每集群一套 collector, 推到中心 Loki, 用租户头区分< / td > < td > 跨集群直连要打通网络与证书,故障域会连成一片< / td > < td > 统一租户命名,中心侧按租户限流< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 最容易被忽略的是采集链路本身:它制造流量。日志量翻倍时先撑不住的是出口带宽与 Loki 的写入,不是磁盘。所以先定「哪些 namespace 必须收、哪些采样」,再谈扩容。< / p >
< h3 id = "sec-12-10" > 12.10 清理< / h3 >
< p > 三个 release 都要删, PVC 要单独删。Helm 卸载不删 PVC, 这是设计如此。< / p >
< pre data-lang = "bash" data-name = "卸载本章的全部产物" > # env: all
# 影响:删掉 platform 里的 grafana、alloy、loki 三个 release, 以及 Loki 的 PVC 与管理员 Secret
helm uninstall grafana alloy loki -n platform
kubectl -n platform get pvc
kubectl -n platform delete pvc storage-loki-0
kubectl -n platform delete secret grafana-admin
kubectl -n platform get all,secret,pvc< / pre >
< p > 三条 < code > uninstall< / code > 之后 < code > get pvc< / code > 里 < code > storage-loki-0< / code > 还在;删完 PVC 与 Secret, < code > get all,secret,pvc< / code > 应只剩 < code > No resources found< / code > 。PVC 卡在 < code > Terminating< / code > 就看 finalizer: < code > local-path< / code > 的清理 Pod 要能调度回原节点。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点:卸载之后磁盘没释放< / span >
< p > < b > 现象< / b > : < code > helm uninstall loki< / code > 成功,< code > kubectl -n platform get pods< / code > 空了,但节点磁盘没变。< / p >
< p > < b > 原因< / b > : Helm 只删它创建的对象, PVC 与手工建的 Secret 不在 release 里,留下的是「孤儿」。< / p >
< p > < b > 怎么验证< / b > : < code > kubectl -n platform get pvc,secret< / code > 还能看到 < code > storage-loki-0< / code > 与 < code > grafana-admin< / code > ,手动删掉;再 < code > kubectl get pv< / code > 确认没有 < code > Released< / code > 的残留 PV。< / p >
< / div >
< h3 id = "sec-12-11" > 12.11 小结与自测< / h3 >
< p class = "take" > stdout 是日志的入口,节点磁盘是第一个家。< / p >
< p class = "take" > Pod 一删, kubelet 连目录一起删,< code > --previous< / code > 也救不回。< / p >
< p class = "take" > 采集器是 DaemonSet, 因为它读的是每个节点自己的文件。< / p >
< p class = "take" > Helm 的历史只增不改,回滚是一次新的变更。< / p >
< p class = "take" > 查询靠标签,定位靠 id, 别把 id 塞进标签。< / p >
< p > 这一章真正的转变不是装了三个组件,而是把日志当成有 schema 的数据:字段固定才能按 < code > path< / code > 聚合、按 < code > trace_id< / code > 定位,标签选对才能不炸索引。< code > trace_id< / code > 没做成标签,就因为每个请求都不同。< / p >
< p > 要记住:本章的 id 只覆盖最后一跳,它没解决跨服务追踪;真要跨服务,得在每一跳注入 header, 那要改 < code > shop-web< / code > 的镜像。< / p >
< details >
< summary > 自测 1( 概念) : 为什么 < code > singleBinary.replicas< / code > 必须显式写 1< / summary >
< p > chart 默认 0, 单机模式又依赖它判断要不要起副本, 不写就是零副本。< code > deploymentMode< / code > 选形态,这个值决定真跑几个进程。< / p >
< / details >
< details >
< summary > 自测 2( 排错) : < code > {namespace="shop"}< / code > 有数据,< code > {app="shop-api"}< / code > 没有,查哪里< / summary >
< p > 先看 < code > discovery.relabel< / code > 取的是不是 < code > __meta_kubernetes_pod_label_app_kubernetes_io_name< / code > ——标签名里的点和斜杠会换成下划线;再看 < code > kubectl -n shop get pods --show-labels< / code > 。< / p >
< / details >
< details >
< summary > 自测 3( 决策) : 保留 30 天、磁盘只有 100Gi, 先动哪个旋钮< / summary >
< p > 先算写入量 × 天数 × 副本。能压的是写入量和副本数,保留天数由合规定。冷热分层比加盘便宜。< / p >
< / details >
< div class = "box tip" >
< span class = "bt" > 延伸挑战< / span >
< p > 让 < code > shop-web< / code > 也输出 JSON, 把收到的 < code > X-Trace-Id< / code > 写进访问日志。改完同一次请求在 Loki 里有两行、标签不同、id 相同。提示:< code > shop-web< / code > 镜像不在本仓库,得先补 Dockerfile。< / p >
< / div >
< h3 id = "sec-12-12" > 12.12 衔接:从「这一条日志」到「整体失败率」< / h3 >
< p > < b > 回收< / b > :本章留下 < code > platform< / code > 里 < code > loki< / code > 、< code > grafana< / code > 、< code > alloy< / code > 三个 release, < code > storage-loki-0< / code > 这个 PVC, < code > grafana-admin< / code > 这个 Secret, 以及 < code > shop-api:v1.3.0< / code > ; < code > shop< / code > 里的工作负载没变,只是日志格式变了。< / p >
< p > < b > 钩子< / b > :日志能回答「这一次请求发生了什么」,回答不了「失败率多少、从几点开始、要不要扩容」。< code > shop-api< / code > 的 < code > /metrics< / code > 目前只有一个 < code > shop_api_requests_total< / code > ,没有延迟分布,也没有告警规则。第 13 章把 kube-prometheus-stack 装进同一个 < code > platform< / code > ,让 HPA 按 CPU 扩缩、5xx 超阈值时报警,并解释 Prometheus 的标签策略为什么和 Loki 不同。下一页:< a href = "13-metrics.html" > 第 13 章 指标、扩缩与告警< / a > 。< / p >
< h3 id = "sec-12-13" > 12.13 参考与验证版本< / h3 >
< ul >
< li > < a href = "https://kubernetes.io/docs/concepts/cluster-administration/logging/" > Kubernetes · Logging Architecture< / a > (节点日志目录、轮转、< code > kubectl logs< / code > 的读取路径)< / li >
< li > < a href = "https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/" > Kubernetes · Kubelet configuration API< / a > ( < code > containerLogMaxSize< / code > 、< code > containerLogMaxFiles< / code > 、< code > podLogsDir< / code > 的默认值)< / li >
< li > < a href = "https://grafana.com/docs/loki/latest/" > Grafana Loki 文档< / a > ( 单机模式、filesystem 存储、LogQL) < / li >
< li > < a href = "https://grafana.com/docs/alloy/latest/reference/components/loki/loki.source.file/" > Alloy · loki.source.file< / a > ( < code > targets< / code > 、< code > file_match< / code > 、positions 文件)< / li >
< li > < a href = "https://grafana.com/docs/alloy/latest/reference/components/discovery/discovery.relabel/" > Alloy · discovery.relabel< / a > (标签改写与 < code > __path__< / code > 的构造)< / li >
< li > < a href = "https://github.com/grafana-community/helm-charts" > grafana-community/helm-charts< / a > (本章 Loki 与 Grafana 的 chart 来源)< / li >
< / ul >
< p > 验证版本: k8s v1.36 / helm v4.3.1 / loki chart 21.2.0( Loki 3.7.9) / grafana chart 14.4.1( Grafana 13.3.1) / alloy chart 1.15.0( Alloy v1.21.3) · 最后验证: 2026-11-11< / p >
< p > 变更记录: 2026-11-11 初版,按 chart 21.x 的 < code > Monolithic< / code > 命名与社区仓库来源编写;此前文档里的 < code > SingleBinary< / code > 写法已标为旧名。< / p >
< / article >
< nav class = "pager" >
< a class = "prev" href = "11-multisvc.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 11 章 · 多服务与网络策略< / span > < / a >
< a class = "next" href = "13-metrics.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 13 章 · 指标、扩缩与告警< / span > < / a >
< / nav >
< p class = "foot" >
Kubernetes 专题 · S3 第 12 章 日志:从 kubectl logs 到可检索< br >
< a href = "index.html" > 总目录< / a > · < a href = "../../index.html" > 知识库首页< / a > · < a href = "../../SRE工程师/sre-learning-path/index.html" > SRE 学习路径< / a >
< / p >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "knowledge/kubernetes" data-portal-label = "知识库 › Kubernetes 专题知识库" > < / script >
< / body >
< / html >