2026-11-06 15:52:48 +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 > 第 8 章 存储:从 emptyDir 到 StatefulSet · Kubernetes 专题知识库< / title >
< meta name = "description" content = "用 StatefulSet 与 volumeClaimTemplates 给 Postgres 落盘:讲清 PV、PVC、StorageClass 三者的绑定链路, fsGroup 权限、PVC 停在 Pending 时的真实报错、扩容失败的原因,以及本地盘节点亲和在生产里的边界。" >
< meta name = "keywords" content = "StatefulSet, PVC, PV, StorageClass, volumeClaimTemplates, fsGroup, 有状态" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< 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 > 第 8 章< / b >
< / div >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
2026-11-11 12:57:24 +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 > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 8< / i > 存储:从 emptyDir 到 StatefulSet< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-8-1" > 8.1 本章在哪:主线之前与之后< / a > < a class = "toc-a lv3" href = "#sec-8-2" > 8.2 学习目标< / a > < a class = "toc-a lv3" href = "#sec-8-3" > 8.3 场景:一次驱逐之后,商品列表是空的< / a > < a class = "toc-a lv3" href = "#sec-8-4" > 8.4 心智模型:卷、合同与中介< / a > < a class = "toc-a lv3" href = "#sec-8-5" > 8.5 概念与字段速查< / a > < a class = "toc-a lv3" href = "#sec-8-6" > 8.6 动手:让商品数据落盘< / a > < a class = "toc-a lv3" href = "#sec-8-7" > 8.7 验收清单< / a > < a class = "toc-a lv3" href = "#sec-8-8" > 8.8 故障实验室< / a > < a class = "toc-a lv3" href = "#sec-8-9" > 8.9 生产对照< / a > < a class = "toc-a lv3" href = "#sec-8-10" > 8.10 清理与残留检查< / a > < a class = "toc-a lv3" href = "#sec-8-11" > 8.11 小结与自测< / a > < a class = "toc-a lv3" href = "#sec-8-12" > 8.12 衔接< / a > < a class = "toc-a lv3" href = "#sec-8-13" > 8.13 参考与验证版本< / a > < / div > < 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 > < a class = "toc-a" href = "12-logging.html" > < i class = "cn" > 12< / i > 日志:从 kubectl logs 到可检索< / a > < 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 > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 17< / i > 生产集群搭建: kubeadm HA< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 18< / i > 节点、调度与容量< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 19< / i > 安全基线: RBAC 与准入< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 20< / i > GitOps: Helm/Kustomize + Argo CD< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 21< / i > CI/CD 流水线< / span > < span class = "toc-a todo" title = "待写" > < i class = "cn" > 22< / i > 备份、恢复与升级< / span > < 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-06 15:52:48 +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 >
< p class = "chapnav" >
< a href = "index.html" > Kubernetes 专题< / a >
< span > ·< / span >
< span > S2 撑得住:状态、入口与多服务< / span >
< span > ·< / span >
< span > 第 < b class = "pos" > 8< / b > / 26 章< / span >
< / p >
< h2 id = "ch8" > < span class = "n" > 8< / span > 存储:从 emptyDir 到 StatefulSet< / h2 >
< div class = "lead" >
< b > 30 秒速览:< / b > 容器一重建,写在它自己文件系统里的数据就没了,业务不能这么活着。本章给 < code > shop-api< / code >
接一个跑在 StatefulSet 上的 Postgres, 用 < code > volumeClaimTemplates< / code > 给每个副本申请独立卷,
并用「删 Pod → 再查数据」证明持久化真的生效。约 150 分钟,其中 40 分钟在等 PVC 和镜像。
< / div >
< h3 id = "sec-8-1" > 8.1 本章在哪:主线之前与之后< / h3 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 项< / th > < th > 内容< / th > < / tr > < / thead >
< tbody >
< tr > < td > 主线之前< / td > < td > 商品存在 < code > shop-api< / code > 进程内存里,扩容副本后每个副本的数据还不一样< / td > < / tr >
< tr > < td > 主线之后< / td > < td > Postgres 独立运行,数据在 PVC 上;删 Pod、重建 Pod、升级镜像都不丢< / td > < / tr >
< tr > < td > 本章产物< / td > < td > < code > deploy/base/postgres.yaml< / code > 、< code > Makefile< / code > 里的 < code > verify-ch08< / code > < / td > < / tr >
< tr > < td > 适用环境< / td > < td > ENV-A( Win11+WSL2+kind) 必做; PVC 扩容实验需 ENV-C, 原因见 < a href = "#sec-8-6" > 8.6< / a > 的 Step 7< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-8-2" > 8.2 学习目标< / h3 >
< div class = "box note" >
< span class = "bt" > 学完你能< / span >
< ul >
< li > 用 < code > volumeClaimTemplates< / code > 给每个副本申请独立卷,判定标准:< code > kubectl get pvc< / code > 里出现 < code > data-postgres-0< / code > 且为 < code > Bound< / code > 。< / li >
< li > 解释 < code > StorageClass< / code > 缺失时 PVC 为什么 < code > Pending< / code > ,判定标准:能从 < code > describe pvc< / code > 的 Events 里读出 < code > storageclass not found< / code > 。< / li >
< li > 用「删 Pod 再查数据」证明持久化生效,判定标准:删除前后 < code > count(*)< / code > 相等。< / li >
< li > 说清数据库为什么不能用 < code > Deployment< / code > + 共享 PVC, 判定标准: 能指出两个副本同时写同一目录的后果。< / li >
< / ul >
< / div >
< h3 id = "sec-8-3" > 8.3 场景:一次驱逐之后,商品列表是空的< / h3 >
< p > 周五 18:40, < code > shop-api< / code > 的一个 Pod 因为节点内存压力被 kubelet 驱逐(< code > Evicted< / code > ) 。40 秒后
Deployment 在另一个节点拉起了新 Pod, 接口却全部返回 500——商品列表是空的。< / p >
< p > 值班的人先以为是自己扩容搞的,把副本数从 3 调到 1, 空的; 又怀疑 Service 选错了 Pod,
< code > kubectl get endpoints< / code > 看到的地址是对的;最后在日志里翻到启动那一行:< / p >
< pre data-lang = "text" data-name = "新 Pod 的第一行日志" > loaded 0 products from in-memory store< / pre >
< div class = "box danger" >
< span class = "bt" > 现象< / span >
< p > 数据从来没出过进程内存。重启不是「恢复」,是「清零」。更麻烦的是当时有 3 个副本,
每个副本各存一份不同的商品,用户刷新页面会看到三种价格。< / p >
< / div >
< p > 本章要做的,就是把「数据在哪」从 Pod 里搬出来——在 K8s 里这个动作叫声明一个 PVC。< / p >
< h3 id = "sec-8-4" > 8.4 心智模型:卷、合同与中介< / h3 >
< figure class = "figure" >
< svg viewBox = "0 0 720 340" role = "img" aria-label = "Deployment 与 StatefulSet 到 PVC、StorageClass、PV 的两条路径" >
< defs >
< marker id = "a8" 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 >
< / defs >
< rect x = "18" y = "16" width = "216" height = "58" rx = "9" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "126" y = "40" text-anchor = "middle" font-size = "14" style = "fill:var(--ink)" > Deployment< / text >
< text x = "126" y = "60" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 无状态,副本可互换< / text >
< rect x = "452" y = "16" width = "250" height = "58" rx = "9" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "577" y = "40" text-anchor = "middle" font-size = "14" style = "fill:var(--ink)" > StatefulSet< / text >
< text x = "577" y = "60" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 有身份,副本不可互换< / text >
< rect x = "60" y = "128" width = "196" height = "46" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "158" y = "156" text-anchor = "middle" font-size = "13" style = "fill:var(--brand)" > PVC data-postgres-0< / text >
< rect x = "330" y = "128" width = "196" height = "46" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "428" y = "156" text-anchor = "middle" font-size = "13" style = "fill:var(--brand)" > PVC data-postgres-1< / text >
< rect x = "250" y = "206" width = "180" height = "42" rx = "8" style = "fill:var(--soft);stroke:var(--line)" > < / rect >
< text x = "340" y = "232" text-anchor = "middle" font-size = "13" style = "fill:var(--ink)" > StorageClass standard< / text >
< rect x = "60" y = "278" width = "150" height = "38" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "135" y = "302" text-anchor = "middle" font-size = "12" style = "fill:var(--ink)" > PV 8Gi< / text >
< rect x = "360" y = "278" width = "150" height = "38" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "435" y = "302" text-anchor = "middle" font-size = "12" style = "fill:var(--ink)" > PV 8Gi< / text >
< path d = "M100,74 L140,124" style = "stroke:var(--danger);fill:none" stroke-dasharray = "6 5" marker-end = "url(#a8)" > < / path >
< text x = "20" y = "108" font-size = "11.5" style = "fill:var(--danger)" > 所有副本抢同一个卷< / text >
< path d = "M520,74 L470,124" style = "stroke:var(--muted);fill:none" marker-end = "url(#a8)" > < / path >
< path d = "M614,74 L600,110 L240,110 L172,124" style = "stroke:var(--muted);fill:none" marker-end = "url(#a8)" > < / path >
< path d = "M158,174 L300,206" style = "stroke:var(--muted);fill:none" marker-end = "url(#a8)" > < / path >
< path d = "M428,174 L382,206" style = "stroke:var(--muted);fill:none" marker-end = "url(#a8)" > < / path >
< path d = "M300,248 L180,276" style = "stroke:var(--muted);fill:none" marker-end = "url(#a8)" > < / path >
< path d = "M380,248 L420,276" style = "stroke:var(--muted);fill:none" marker-end = "url(#a8)" > < / path >
< text x = "452" y = "266" font-size = "11.5" style = "fill:var(--muted)" > 动态供给< / text >
< / svg >
< div class = "figcap" > < b > 图 1 ·< / b > 一份卷从 YAML 申请到真正有存储,中间经过谁、什么条件下会停在 < code > Pending< / code > 。< / div >
< / figure >
< p > 见图 1 的两条路径: Deployment 的副本全部指向同一个 PVC( 虚线, 就是上一节那次事故的走法) ,
StatefulSet 的每个副本各有自己的 PVC; 两条路径最后都要经过 StorageClass 才会产生 PV。
差别不在「能不能挂上卷」,而在「卷属不属于这个副本」。< / p >
< p > 换成生活里的说法:< code > PV< / code > 是房子,< code > PVC< / code > 是租房合同,< code > StorageClass< / code > 是中介。
你只签合同(写 YAML) , 中介负责找房( 动态供给) , < code > StatefulSet< / code > 保证每个员工(副本)签的是自己那份合同。< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 常见误解< / th > < th > 事实< / th > < / tr > < / thead >
< tbody >
< tr > < td > 「Pod 重启后 IP 不变,卷也还在」< / td > < td > Pod 重建后 IP 会变;卷是否还在取决于 PVC, 与 Pod 无关< / td > < / tr >
< tr > < td > 「PVC 写完就自动有存储」< / td > < td > 没有可用 < code > StorageClass< / code > 或没有 PV 时, PVC 会一直 < code > Pending< / code > < / td > < / tr >
< tr > < td > 「数据库多开几个副本就高可用」< / td > < td > 多个副本挂同一个 < code > ReadWriteOnce< / code > 卷会写坏数据;主从要靠 StatefulSet + 复制协议< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-8-5" > 8.5 概念与字段速查< / h3 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 对象 / 字段< / th > < th > 作用< / th > < th > 默认值< / th > < th > 生产建议< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > emptyDir< / code > < / td > < td > Pod 生命周期内的临时目录< / td > < td > 随 Pod 删除< / td > < td > 只放缓存与临时文件< / td > < / tr >
< tr > < td > < code > PersistentVolumeClaim< / code > < / td > < td > 存储申请单,绑定后独立于 Pod< / td > < td > 无< / td > < td > 每份数据一个 PVC, 不要共用< / td > < / tr >
< tr > < td > < code > spec.storageClassName< / code > < / td > < td > 指定由谁供给< / td > < td > 集群默认 SC( 若有) < / td > < td > 显式写,不依赖默认值< / td > < / tr >
< tr > < td > < code > spec.accessModes< / code > < / td > < td > 访问模式< / td > < td > 必填< / td > < td > 数据库一律 < code > ReadWriteOnce< / code > < / td > < / tr >
< tr > < td > < code > requests.storage< / code > < / td > < td > 申请容量< / td > < td > 必填< / td > < td > 留 30% 余量;能否扩容看 SC< / td > < / tr >
< tr > < td > < code > persistentVolumeReclaimPolicy< / code > < / td > < td > PVC 删除后 PV 怎么办< / td > < td > < code > Delete< / code > (动态供给)< / td > < td > 核心数据 < code > Retain< / code > + 快照< / td > < / tr >
< tr > < td > < code > volumeClaimTemplates< / code > < / td > < td > 给每个副本生成独立 PVC< / td > < td > 无< / td > < td > 命名规则 < code > < 模板名> -< Pod 名> < / code > < / td > < / tr >
< tr > < td > < code > spec.serviceName< / code > < / td > < td > 提供稳定 DNS 的 headless Service< / td > < td > 必填< / td > < td > 与 StatefulSet 同名约定< / td > < / tr >
< tr > < td > < code > securityContext.fsGroup< / code > < / td > < td > 让卷的属组可写< / td > < td > 无< / td > < td > 数据库镜像必须配( postgres:16 是 999) < / td > < / tr >
< tr > < td > < code > volumeBindingMode< / code > < / td > < td > 何时绑定 PV< / td > < td > < code > Immediate< / code > < / td > < td > 本地盘用 < code > WaitForFirstConsumer< / code > < / td > < / tr >
< / tbody >
< / table >
< / div >
< details >
< summary > 可跳过 · < code > ReadWriteMany< / code > 到底谁支持< / summary >
< p > < code > RWO< / code > / < code > ROX< / code > / < code > RWX< / code > 描述的是< b > 挂载语义< / b > ,不是文件系统权限。
块存储( 云盘、Ceph RBD、本地盘) 在协议层就不允许同一卷被多节点同时写, 所以一律 < code > RWO< / code > ;
< code > RWX< / code > 只能由网络文件系统提供( NFS、CephFS、云厂商的文件存储) 。kind 的 < code > local-path< / code >
是本机目录,只有 < code > RWO< / code > ,这也是下面 Step 6 只能在一台机器上连库的原因。< / p >
< / details >
< p class = "take" > < b > 一句话:< / b > 副本数解决「活几个」,卷解决「数据在哪」,这是两件事。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · serviceName 填普通 Service 也能起来< / span >
< p > < b > 现象< / b > : StatefulSet 照样 < code > Running< / code > , < code > kubectl get pods< / code > 正常;但
< code > nslookup postgres-0.postgres-headless< / code > 解析不到,主从配置、< code > pg_basebackup< / code >
这类「按 Pod 名找节点」的操作全部失败。< / p >
< p > < b > 原因< / b > : < code > serviceName< / code > 指向的必须是 headless Service( < code > clusterIP: None< / code > ) ,
控制器才会为每个 Pod 建 < code > < pod> .< svc> < / code > 形式的稳定 DNS 记录;普通 Service 只有集群 VIP, 没有单 Pod 名字。< / p >
< p > < b > 怎么验证< / b > : < code > kubectl get svc postgres-headless -n shop -o jsonpath='{.spec.clusterIP}'< / code >
应返回 < code > None< / code > ;再在任意 Pod 里 < code > nslookup postgres-0.postgres-headless< / code > ,应解析到 < code > postgres-0< / code > 的 IP。< / p >
< / div >
< h3 id = "sec-8-6" > 8.6 动手:让商品数据落盘< / h3 >
< p > 八个步骤按顺序做,每步都能单独验证;工作目录是 < code > ~/work/aurora-shop< / code > 。< / p >
< h4 > Step 1 · 校验上一章状态< / h4 >
< p > < span class = "tag" > 意图< / span > 确认起点干净,探针与资源限制都在。< / p >
< pre data-lang = "bash" data-name = "校验 ch07" > # env: all
make verify-ch07< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
[ok] deployment shop-api ready 3/3
[ok] probes configured
[ok] resources requests/limits configured< / pre >
< h4 > Step 2 · 写一份带卷的清单,观察 PVC 自动生成< / h4 >
< p > < span class = "tag" > 意图< / span > 一次写完 headless Service、客户端 Service、StatefulSet 三个对象。< / p >
< pre data-lang = "yaml" data-name = "deploy/base/postgres.yaml" > # file: deploy/base/postgres.yaml
apiVersion: v1
2026-11-08 15:27:37 +08:00
kind: Secret
metadata:
name: shop-db # 本章新建: postgres 的账号口令,与 shop-secret 里的 DATABASE_URL 同一套
namespace: shop
labels:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
type: Opaque
stringData:
POSTGRES_USER: shop
POSTGRES_PASSWORD: aurora-local-dev
---
apiVersion: v1
2026-11-06 15:52:48 +08:00
kind: Service
metadata:
name: postgres-headless # 给 StatefulSet 提供稳定 DNS: postgres-0.postgres-headless
namespace: shop
labels:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
spec:
clusterIP: None # headless: 不做负载均衡, 直接返回 Pod IP
selector:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
ports:
- name: pg
port: 5432
targetPort: 5432
---
apiVersion: v1
kind: Service
metadata:
name: postgres # 给业务用:普通 ClusterIP, 交给 kube-proxy 选一个 Pod
namespace: shop
labels:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
spec:
selector:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
ports:
- name: pg
port: 5432
targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: shop
labels:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
app.kubernetes.io/version: "16"
spec:
serviceName: postgres-headless
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
template:
metadata:
labels:
app.kubernetes.io/name: postgres
app.kubernetes.io/instance: shop
app.kubernetes.io/version: "16"
spec:
securityContext:
fsGroup: 999 # postgres:16(Debian) 的 uid/gid 是 999; alpine 版是 70
fsGroupChangePolicy: OnRootMismatch
containers:
- name: postgres
image: postgres:16
ports:
- name: pg
containerPort: 5432
envFrom:
- secretRef:
2026-11-08 15:27:37 +08:00
name: shop-db # 与清单第一段同一个对象: POSTGRES_USER / POSTGRES_PASSWORD
2026-11-06 15:52:48 +08:00
env:
- name: POSTGRES_DB
value: shop
- name: PGDATA
value: /var/lib/postgresql/data/pgdata # 卷下再建子目录,避开挂载点的 lost+found
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
resources:
requests:
cpu: 200m
memory: 512Mi
limits:
memory: 1Gi
readinessProbe:
exec:
command: ["pg_isready", "-U", "shop", "-d", "shop"]
initialDelaySeconds: 5
periodSeconds: 5
volumeClaimTemplates: # 每个副本一份独立 PVC, 命名 data-postgres-0
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: standard
resources:
requests:
storage: 8Gi< / pre >
< pre data-lang = "bash" data-name = "应用清单" > # env: all
kubectl apply -f deploy/base/postgres.yaml< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
service/postgres-headless created
service/postgres created
statefulset.apps/postgres created< / pre >
< p > < code > apply< / code > 之后 < code > volumeClaimTemplates< / code > 会立刻为每个副本生成一份 PVC。
三个对象各管一件事,别混着用:< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 对象< / th > < th > 谁在用< / th > < th > 地址< / th > < th > 换成另一个会怎样< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > Service postgres-headless< / code > < / td > < td > StatefulSet 的 < code > serviceName< / code > 、运维、主从配置< / td > < td > < code > postgres-0.postgres-headless.shop.svc< / code > < / td > < td > 填普通 Service 也能起,但单 Pod DNS 记录消失< / td > < / tr >
< tr > < td > < code > Service postgres< / code > < / td > < td > < code > shop-api< / code > 的业务连接< / td > < td > < code > postgres.shop.svc.cluster.local:5432< / code > < / td > < td > 业务直连 < code > postgres-0< / code > 就绑死了具体副本,扩缩容即断< / td > < / tr >
< tr > < td > < code > StatefulSet postgres< / code > < / td > < td > 控制器,管理 Pod 与 PVC< / td > < td > —< / td > < td > 换成 Deployment 就不再保证名字与卷的对应关系< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 看懂这层对应关系,后面所有「卷到底从哪来」的问题都能自己回答。< / p >
< pre data-lang = "bash" data-name = "观察 PVC 与 Pod" > # env: all
kubectl get pvc -n shop
kubectl get pods -n shop -l app.kubernetes.io/name=postgres -o wide< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS
data-postgres-0 Bound pvc-3f1c9a2e-... 8Gi RWO standard
NAME READY STATUS RESTARTS AGE IP NODE
postgres-0 1/1 Running 0 45s 10.244.1.7 aurora-worker< / pre >
< div class = "box warn" >
< span class = "bt" > 如果不一样 · PVC 一直 Pending< / span >
< p > < code > kubectl describe pvc data-postgres-0 -n shop< / code > 看 Events 最后一行:< code > storageclass not found< / code >
是名字写错;< code > no persistent volumes available< / code > 是集群里没有默认 SC( 回第 1 章确认 kind 已装 < code > standard< / code > )。
另一种情况是 < code > error: unable to recognize< / code > ——文件里混了 tab, 用 < code > grep -P "\t" deploy/base/postgres.yaml< / code > 查。< / p >
< / div >
< div class = "box warn" >
< span class = "bt" > 易错点 · 改 volumeClaimTemplates 的容量再 apply 会失败< / span >
< p > < b > 现象< / b > :把 < code > storage: 8Gi< / code > 改成 < code > 12Gi< / code > 后 < code > kubectl apply< / code > 报
< code > The StatefulSet "postgres" is invalid: spec: Forbidden: updates to statefulset spec for fields other than
'replicas', 'ordinals', 'template', 'updateStrategy', 'revisionHistoryLimit',
'persistentVolumeClaimRetentionPolicy' and 'minReadySeconds' are forbidden< / code > 。< / p >
< p > < b > 原因< / b > : < code > volumeClaimTemplates< / code > 在 StatefulSet 创建后不可变;它生成的 PVC 是独立对象,
改模板不会回头改已存在的 PVC。< / p >
< p > < b > 怎么验证< / b > : < code > kubectl get pvc data-postgres-0 -n shop -o jsonpath='{.spec.resources.requests.storage}'< / code >
仍是 < code > 8Gi< / code > 。要扩容只能 patch PVC 本身(见 Step 7) 。< / p >
< / div >
< h4 > Step 3 · 故意写错 StorageClass( 负向) < / h4 >
< p > < span class = "tag" > 意图< / span > 先亲眼看一次 < code > Pending< / code > ,以后才不会把它当成「卡住了」。< / p >
< pre data-lang = "bash" data-name = "换成一个不存在的 SC" > # env: all
kubectl delete -f deploy/base/postgres.yaml
# 影响:删除 StatefulSet 与两个 Service, Pod 随之终止; PVC 不会被自动删除
kubectl delete pvc data-postgres-0 -n shop
# 影响:连带删除 PV, 数据不可恢复( 本章此时还没有业务数据)
sed -i 's/storageClassName: standard/storageClassName: fast-ssd/' deploy/base/postgres.yaml
kubectl apply -f deploy/base/postgres.yaml< / pre >
< pre data-lang = "bash" data-name = "观察 Pending" > # env: all
kubectl get pvc -n shop
kubectl get pods -n shop -l app.kubernetes.io/name=postgres< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS
data-postgres-0 Pending fast-ssd
NAME READY STATUS RESTARTS AGE
postgres-0 0/1 Pending 0 12s
# describe pvc 的 Events 最后一行
Warning ProvisioningFailed storageclass.storage.k8s.io "fast-ssd" not found< / pre >
< div class = "box warn" >
< span class = "bt" > 为什么错,怎么改回来< / span >
< p > < code > storageClassName< / code > 指向一个不存在的供给者, PVC 永远等不到 PV, Pod 因为卷没绑定而调度不出去
( Events 里是 < code > pod has unbound immediate PersistentVolumeClaims< / code > )。改成:< / p >
< pre data-lang = "bash" data-name = "改回 standard" > # env: all
sed -i 's/storageClassName: fast-ssd/storageClassName: standard/' deploy/base/postgres.yaml
kubectl delete sts postgres -n shop
kubectl delete pvc data-postgres-0 -n shop
kubectl apply -f deploy/base/postgres.yaml< / pre >
< p > 两条 < code > delete< / code > 会丢弃 < code > data-postgres-0< / code > 里的全部数据。本章此时还没有业务数据所以安全,
生产环境禁止这样操作,见第 22 章。< / p >
< / div >
< h4 > Step 4 · 让 shop-api 连上数据库< / h4 >
< p > < span class = "tag" > 意图< / span > 把连接串从「内存开关」换成真实地址,顺便验证两个 Service 的分工。< / p >
< pre data-lang = "bash" data-name = "改 ConfigMap 并滚动" > # env: all
kubectl patch configmap shop-config -n shop --type merge \
-p '{"data":{"DB_HOST":"postgres.shop.svc.cluster.local","DB_PORT":"5432"}}'
kubectl rollout restart deployment/shop-api -n shop
kubectl rollout status deployment/shop-api -n shop< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
deployment.apps/shop-api restarted
Waiting for deployment "shop-api" rollout to finish: 1 out of 3 new replicas have been updated...
deployment "shop-api" successfully rolled out< / pre >
< pre data-lang = "bash" data-name = "验证接口有数据" > # env: all
kubectl exec -n shop deploy/shop-api -- wget -qO- http://localhost:8080/api/products | head -c 200< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
[{"id":1,"name":"极光马克杯","price":39},{"id":2,"name":"极光帆布袋","price":59}]< / pre >
< div class = "box warn" >
< span class = "bt" > 如果不一样 · no such host< / span >
< p > < code > dial tcp: lookup postgres on 10.96.0.10:53: no such host< / code > 是 DNS 问题:先
< code > kubectl get svc -n shop< / code > 确认 < code > postgres< / code > 存在,再在 Pod 里
< code > nslookup postgres.shop.svc.cluster.local< / code > 。业务连的是 < code > postgres< / code > ( ClusterIP) ,
不是 < code > postgres-0.postgres-headless< / code > ——后者是单点直连,只适合运维和主从配置。< / p >
< / div >
< h4 > Step 5 · 证明数据真的持久< / h4 >
< p > < span class = "tag" > 意图< / span > 这是本章唯一有说服力的验收。< code > shop-api< / code > 启动时会执行
< code > CREATE TABLE IF NOT EXISTS products< / code > 并写入 2 条种子数据,所以第一次查应该是 2 行。< / p >
< pre data-lang = "bash" data-name = "写一行再数一次" > # env: all
kubectl exec -n shop postgres-0 -- psql -U shop -d shop \
-c "INSERT INTO products(name,price) VALUES('持久化测试', 1);"
kubectl exec -n shop postgres-0 -- psql -U shop -d shop -c "SELECT count(*) FROM products;"< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
INSERT 0 1
count
-------
3< / pre >
< pre data-lang = "bash" data-name = "删 Pod 再数一次" > # env: all
kubectl delete pod postgres-0 -n shop
kubectl wait --for=condition=Ready pod/postgres-0 -n shop --timeout=120s
kubectl exec -n shop postgres-0 -- psql -U shop -d shop -c "SELECT count(*) FROM products;"< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
pod "postgres-0" deleted
pod/postgres-0 condition met
count
-------
3< / pre >
< p > 新 Pod 还叫 < code > postgres-0< / code > ( StatefulSet 保证名字不变),挂的还是同一个 PVC
< code > data-postgres-0< / code > ,所以数据还在。反过来,把 < code > shop-api< / code > 的 Pod 删掉,它重启后读到的也是这 3 行——
但它自己不再持有数据。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · 缩容到 0 之后 PVC 会一直留着< / span >
< p > < b > 现象< / b > : < code > kubectl scale sts postgres --replicas=0< / code > 之后 Pod 没了,
< code > kubectl get pvc -n shop< / code > 里 < code > data-postgres-0< / code > 还在,继续占着存储和账单。< / p >
< p > < b > 原因< / b > : < code > persistentVolumeClaimRetentionPolicy< / code > 未设置时两个策略都是 < code > Retain< / code > ,
删 Pod、缩容都不动 PVC——为了防「误缩容丢数据」, 代价是卷会攒下来。< / p >
< p > < b > 怎么验证< / b > : < code > kubectl get sts postgres -n shop -o jsonpath='{.spec.persistentVolumeClaimRetentionPolicy}'< / code >
输出为空即保留;缩容后 < code > kubectl get pvc -n shop< / code > 仍能看到它。< / p >
< / div >
< h4 > Step 6 · 用客户端从宿主机连进去< / h4 >
< p > < span class = "tag" > 意图< / span > 确认卷在集群里,也能被你的电脑访问,顺便看清两个环境的网络差异。< / p >
< div class = "grid2" >
< div class = "box" >
< h4 > Windows 11 + WSL2< / h4 >
< pre data-lang = "bash" data-name = "在 WSL 里转发端口" > # env: wsl
kubectl port-forward -n shop svc/postgres 15432:5432< / pre >
< p > Windows 侧用 DBeaver 连 < code > 127.0.0.1:15432< / code > ,用户 < code > shop< / code > ,库 < code > shop< / code > 。
WSL2 的 localhost 转发会把端口透到 Windows。< / p >
< / div >
< div class = "box" >
< h4 > Linux (Ubuntu 24.04)< / h4 >
< pre data-lang = "bash" data-name = "转发并直接用 psql 连" > # env: linux
kubectl port-forward -n shop svc/postgres 15432:5432 &
psql "postgresql://shop@127.0.0.1:15432/shop" -c "select version();"< / pre >
< p > 本机已装 < code > psql< / code > ,转发后直接连,不需要图形客户端。< / p >
< / div >
< / div >
< p > < b > 差异结论< / b > : < code > port-forward< / code > 两边命令一样, 差异在客户端——Windows 上必须另装一个图形客户端,
WSL2 的 localhost 转发能把端口透到 Windows, 但不会把 < code > psql< / code > 一起带过去。< / p >
< h4 > Step 7 · 扩容卷(在 ENV-A 上会失败,这很重要)< / h4 >
< p > < span class = "tag" > 意图< / span > 认识 < code > local-path< / code > 这类本地供给者的边界。< / p >
< pre data-lang = "bash" data-name = "尝试把 8Gi 扩到 16Gi" > # env: all
kubectl patch pvc data-postgres-0 -n shop -p '{"spec":{"resources":{"requests":{"storage":"16Gi"}}}}'< / pre >
< pre data-lang = "text" data-name = "预期输出( kind 的 standard 未开启 allowVolumeExpansion) " > # 预期输出
error: persistentvolumeclaims "data-postgres-0" is forbidden: only dynamically provisioned pvc can be
resized and the storageclass that provisions the pvc must support resize< / pre >
< p > API 直接拒绝, PVC 仍是 8Gi, 不需要撤销。如果 SC 开了 < code > allowVolumeExpansion: true< / code >
但底层不支持,则会看到 PVC 卡在 < code > Resizing< / code > , < code > kubectl describe pvc< / code > 的 Events 里有
< code > ExternalExpanding< / code > / < code > resize not supported< / code > 。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 168" role = "img" aria-label = "PVC 从 Pending 到 Bound、Resizing、FileSystemResizePending 的状态迁移" >
< defs >
< marker id = "a9" 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 >
< / defs >
< rect x = "14" y = "58" width = "120" height = "44" rx = "8" style = "fill:var(--soft);stroke:var(--line)" > < / rect >
< text x = "74" y = "85" text-anchor = "middle" font-size = "13" style = "fill:var(--ink)" > Pending< / text >
< rect x = "190" y = "58" width = "120" height = "44" rx = "8" style = "fill:var(--ok-bg);stroke:var(--ok)" > < / rect >
< text x = "250" y = "85" text-anchor = "middle" font-size = "13" style = "fill:var(--ok)" > Bound< / text >
< rect x = "366" y = "58" width = "120" height = "44" rx = "8" style = "fill:var(--warn-bg);stroke:var(--warn)" > < / rect >
< text x = "426" y = "85" text-anchor = "middle" font-size = "13" style = "fill:var(--warn)" > Resizing< / text >
< rect x = "536" y = "58" width = "168" height = "44" rx = "8" style = "fill:var(--warn-bg);stroke:var(--warn)" > < / rect >
< text x = "620" y = "78" text-anchor = "middle" font-size = "12.5" style = "fill:var(--warn)" > FileSystem< / text >
< text x = "620" y = "94" text-anchor = "middle" font-size = "12.5" style = "fill:var(--warn)" > ResizePending< / text >
< path d = "M134,80 L186,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a9)" > < / path >
< text x = "126" y = "48" font-size = "11.5" style = "fill:var(--muted)" > SC 供给成功< / text >
< path d = "M310,80 L362,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a9)" > < / path >
< text x = "306" y = "48" font-size = "11.5" style = "fill:var(--muted)" > patch 扩容< / text >
< path d = "M486,80 L532,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a9)" > < / path >
< text x = "482" y = "48" font-size = "11.5" style = "fill:var(--muted)" > 块设备已扩< / text >
< path d = "M620,106 L620,136 L250,136 L250,106" style = "stroke:var(--muted);fill:none" marker-end = "url(#a9)" > < / path >
< text x = "390" y = "152" font-size = "11.5" style = "fill:var(--muted)" > kubelet 扩完文件系统,回到 Bound< / text >
< path d = "M74,58 L74,22 L120,22" style = "stroke:var(--danger);fill:none" stroke-dasharray = "5 4" marker-end = "url(#a9)" > < / path >
< text x = "128" y = "26" font-size = "11.5" style = "fill:var(--danger)" > SC 不存在:一直停在 Pending< / text >
< / svg >
< div class = "figcap" > < b > 图 2 ·< / b > 一个 PVC 从申请到扩容会经过哪几个状态,卡住时停在哪一格。< / div >
< / figure >
< p > 见图 2: Step 2 只走了 < code > Pending → Bound< / code > 这一段, Step 7 的扩容在 kind 上连第一步都进不去——
API 直接拒绝,所以状态停在 < code > Bound< / code > ,容量不变。云盘 CSI 才会真的经过 < code > Resizing< / code > ,
中间那段时间 Pod 仍可读写。< / p >
< details >
< summary > 可跳过 · 为什么 kind 的默认 StorageClass 叫 < code > standard< / code > < / summary >
< p > kind 镜像自带 < code > local-path-provisioner< / code > ,并把它注册成名为 < code > standard< / code > 的默认类;
k3s 用同一个 provisioner, 但类名是 < code > local-path< / code > ( ENV-B 上会遇到,第 17 章统一)。
它把 PV 映射到节点上的 < code > /var/local-path-provisioner/< / code > 目录,容量没有真正的配额约束,
也没有快照与克隆能力。< / p >
< / details >
< p > 在 ENV-C 上用支持扩容的 StorageClass( 云盘 CSI 或 < code > allowVolumeExpansion: true< / code > 的 SC)
重做一次,才能看到 < code > FileSystemResizePending → 16Gi< / code > 的完整过程。
< b > 这是「本地能跑」和「生产可用」的第一道分水岭。< / b > < / p >
< p class = "take" > < b > 一句话:< / b > 扩容能不能做,取决于 StorageClass 背后那个存储,不取决于 K8s。< / p >
< h4 > Step 8 · 提交本章产物< / h4 >
< pre data-lang = "bash" data-name = "提交" > # env: all
git add deploy/base/postgres.yaml Makefile
git commit -m "ch08: postgres 落盘, shop-api 改用数据库"< / pre >
< h3 id = "sec-8-7" > 8.7 验收清单< / h3 >
< ol class = "steps" >
< li > < code > kubectl get pvc -n shop< / code > → < code > data-postgres-0< / code > 为 < code > Bound< / code > ,容量 8Gi< / li >
< li > < code > kubectl get sts -n shop< / code > → < code > postgres 1/1< / code > < / li >
< li > 反向验证:< code > kubectl delete pod postgres-0< / code > 后 < code > SELECT count(*)< / code > 与删除前一致< / li >
< li > < code > kubectl get pods -n shop -l app.kubernetes.io/name=postgres -o wide< / code > → Pod 始终叫 < code > postgres-0< / code > < / li >
< li > < code > deploy/base/postgres.yaml< / code > 里 < code > storageClassName< / code > 是显式写的,不是空的< / li >
< li > < code > make verify-ch08< / code > 全绿< / li >
< / ol >
< pre data-lang = "bash" data-name = "一次跑完" > # env: all
make verify-ch08< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
[ok] pvc data-postgres-0 bound 8Gi
[ok] statefulset postgres ready 1/1
[ok] data survives pod deletion (3 rows)
[ok] shop-api connects to postgres< / pre >
< h3 id = "sec-8-8" > 8.8 故障实验室< / h3 >
< div class = "box danger" >
< span class = "bt" > 故障 1 · Postgres 起来了但一直重启< / span >
< p > < b > 注入< / b > :把 < code > securityContext.fsGroup< / code > 整段删掉,< code > kubectl apply< / code > 后
< code > kubectl delete pod postgres-0< / code > 。< / p >
< p > < b > 症状< / b > : < code > STATUS=CrashLoopBackOff< / code > , < code > RESTARTS< / code > 一直涨;
< code > kubectl logs postgres-0 --previous< / code > 里有
< code > initdb: could not change permissions of directory "/var/lib/postgresql/data/pgdata": Operation not permitted< / code > 。< / p >
< p > < b > 诊断< / b > :① < code > kubectl logs --previous< / code > 看第一次启动的报错(当前容器日志可能已经是重启后的);
② 进不去就 < code > kubectl debug -it pod/postgres-0 --image=busybox --target=postgres< / code > 看目录属主:
< code > ls -ld /var/lib/postgresql/data< / code > 显示 < code > root:root< / code > ;
③ 对比镜像默认用户 < code > id postgres< / code > = 999。< / p >
< p > < b > 根因< / b > :卷由 kubelet 以 root 创建,没有 < code > fsGroup< / code > 时容器内的 uid 999 无法写目录,< code > initdb< / code > 直接失败。< / p >
< p > < b > 修复< / b > :加回 < code > securityContext.fsGroup: 999< / code > 与 < code > fsGroupChangePolicy: OnRootMismatch< / code > ,重建 Pod。< / p >
< p > < b > 预防< / b > :所有数据库类 StatefulSet 模板默认带 < code > fsGroup< / code > ;用 Kyverno 策略要求「挂载了 PVC 的 Pod 必须有 securityContext」( 第 19 章)。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 2 · 扩到 2 副本后数据错乱< / span >
< p > < b > 注入< / b > :把 Postgres 改成 < code > Deployment< / code > , < code > replicas: 2< / code > ,两个 Pod 挂< b > 同一个< / b > PVC < code > data-postgres-0< / code > 。< / p >
< p > < b > 症状< / b > :两个 Pod 都 < code > Running< / code > (本地盘不报多挂载错误),但查询时而 3 行时而 5 行,
日志里出现 < code > database files are incompatible with server< / code > 或 < code > could not open file "pg_wal/..."< / code > 。< / p >
< p > < b > 诊断< / b > :① < code > kubectl get pods -o wide< / code > 配合
< code > kubectl get pod -o jsonpath='{.spec.volumes}'< / code > 确认两个 Pod 挂同一 PVC;
② < code > kubectl logs< / code > 看两个实例是否都在跑 < code > initdb< / code > ;
③ 云上会直接看到 < code > Multi-Attach error for volume< / code > ,本地盘不会,< b > 所以更危险< / b > 。< / p >
< p > < b > 根因< / b > : < code > ReadWriteOnce< / code > 约束的是节点级挂载,同一节点上两个 Pod 可以同时写;
Postgres 的数据目录不支持多进程并发写。< / p >
< p > < b > 修复< / b > :换回 < code > StatefulSet< / code > + < code > volumeClaimTemplates< / code > ;真要多副本必须走流复制,不是加 < code > replicas< / code > 。< / p >
< p > < b > 预防< / b > :准入策略里禁止数据库类工作负载用 < code > kind: Deployment< / code > ; Operator 化后由控制器保证拓扑。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 3 · 节点下线后 Postgres 再也起不来< / span >
< p > < b > 注入< / b > : < code > kubectl cordon aurora-worker< / code > ( Postgres 所在节点),再 < code > kubectl delete pod postgres-0< / code > 。< / p >
< p > < b > 症状< / b > :新 Pod 长期 < code > Pending< / code > , < code > describe pod< / code > 的 Events 最后一行是
< code > node(s) had volume node affinity conflict< / code > 。< / p >
< p > < b > 诊断< / b > :① < code > kubectl describe pvc data-postgres-0< / code > 看 < code > Volume< / code > 名;
② < code > kubectl get pv < volume> -o yaml< / code > 看 < code > spec.nodeAffinity< / code > 指向哪个节点;
③ 对比 Pod 被调度到的节点。< / p >
< p > < b > 根因< / b > : < code > local-path< / code > 供给的 PV 是本地目录,带 < code > nodeAffinity< / code > 锁死在原节点;
节点不可调度时, Pod 无处可去。< / p >
< p > < b > 修复< / b > : < code > kubectl uncordon aurora-worker< / code > , Pod 立即能起来。< / p >
< p > < b > 预防< / b > :生产用网络存储(云盘 CSI / CephFS / NFS) 才有跨节点漂移能力; 本地盘只适合缓存、日志、可重建数据( 见第 18 章节点池设计)。< / p >
< / div >
< h3 id = "sec-8-9" > 8.9 生产对照< / h3 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > 学习环境( kind) < / th > < th > 生产环境< / th > < th > 为什么< / th > < th > 迁移动作< / th > < / tr > < / thead >
< tbody >
< tr > < td > 供给者< / td > < td > < code > local-path-provisioner< / code > < / td > < td > 云盘 CSI / Ceph RBD / 企业存储< / td > < td > 本地目录绑死节点,节点故障即数据不可用< / td > < td > 换 < code > storageClassName< / code > ,用 Velero 迁数据< / td > < / tr >
< tr > < td > 扩容< / td > < td > 不支持在线扩容< / td > < td > 云盘支持 < code > allowVolumeExpansion< / code > < / td > < td > 文件系统 resizefs 需要 CSI 支持< / td > < td > 建 SC 时显式 < code > allowVolumeExpansion: true< / code > < / td > < / tr >
< tr > < td > 访问模式< / td > < td > 只有 < code > RWO< / code > < / td > < td > 支持 < code > RWO/RWX/ROX< / code > < / td > < td > 块存储只能单节点挂载;共享文件需要 NFS/CephFS< / td > < td > 数据库 RWO, 共享上传目录 RWX< / td > < / tr >
< tr > < td > 高可用< / td > < td > 单副本,节点挂了就停< / td > < td > 主从 / Patroni / Operator 管理< / td > < td > K8s 不管数据库复制,只保证 Pod 运行< / td > < td > 引入 CloudNativePG 等 Operator( 第 25 章)< / td > < / tr >
< tr > < td > 回收策略< / td > < td > < code > Delete< / code > < / td > < td > 核心数据 < code > Retain< / code > + 快照< / td > < td > 误删 PVC 时 < code > Delete< / code > 会连 PV 一起删< / td > < td > 改 SC 的 < code > reclaimPolicy< / code > ,配快照策略< / td > < / tr >
< / tbody >
< / table >
< / div >
< p class = "take" > < b > 一句话:< / b > 学习环境证明「能跑」,生产环境才证明「能换」——存储方案的差别就在这两个字上。< / p >
< h3 id = "sec-8-10" > 8.10 清理与残留检查< / h3 >
< pre data-lang = "bash" data-name = "清理本章资源" > # env: all
kubectl delete -f deploy/base/postgres.yaml
# 影响:删除 StatefulSet 与两个 Service, PVC 不会自动删除
kubectl delete pvc data-postgres-0 -n shop
# 影响:连同 PV 一起删除,数据不可恢复(本章无重要数据)< / pre >
< pre data-lang = "bash" data-name = "残留检查" > # env: all
kubectl get all,pvc,cm,secret -n shop< / pre >
< pre data-lang = "text" data-name = "预期输出(应只剩第 03– 07 章的对象)" > # 预期输出
pod/shop-api-... 1/1 Running
pod/shop-web-... 1/1 Running
service/shop-api ClusterIP ...
service/shop-web ClusterIP ...
deployment.apps/shop-api
deployment.apps/shop-web< / pre >
< p > 回滚到上一章:< code > git checkout HEAD~1 -- deploy/base/ Makefile< / code > 后跑 < code > make verify-ch07< / code > 。< / p >
< h3 id = "sec-8-11" > 8.11 小结与自测< / h3 >
< p class = "take" > < b > 一句话:< / b > 数据不属于 Pod, 属于 PVC; Pod 是可抛弃的,卷不是。< / p >
< p class = "take" > < b > 一句话:< / b > PVC 卡在 Pending 时,答案永远在 describe 的 Events 最后一行。< / p >
< p class = "take" > < b > 一句话:< / b > 数据库的「多副本」是复制协议的事,不是 < code > replicas: 2< / code > 的事。< / p >
< p > < code > volumeClaimTemplates< / code > 的核心价值是「每个副本一份卷」,这是有状态与无状态的真正分界。< / p >
< details >
< summary > 自测 3 题(点击展开答案)< / summary >
< p > < b > 1( 概念) < / b > < code > ReadWriteOnce< / code > 是「一个 Pod 只能读」吗?< / p >
< p > 不是。< code > RWO< / code > 约束的是< b > 挂载节点数< / b > ,同一节点上多个 Pod 可以同时读写。真正独占要靠文件系统或应用层锁。< / p >
< p > < b > 2( 排错) < / b > PVC 是 < code > Bound< / code > 的, Pod 却 < code > Pending< / code > 且报 < code > volume node affinity conflict< / code > ,你先看什么?< / p >
< p > 先看 PV 的 < code > spec.nodeAffinity< / code > 指向哪个节点,再看 Pod 被调度到哪个节点。本地卷的 PV 被锁在原节点,
节点不可调度时 Pod 无处可去——< code > kubectl uncordon< / code > 或换网络存储。< / p >
< p > < b > 3( 决策) < / b > 团队要存用户上传的图片, 3 个 < code > shop-web< / code > 副本都要读写,选 < code > RWO< / code > 还是 < code > RWX< / code > ? < / p >
< p > 选 < code > RWX< / code > ( NFS/CephFS/对象存储)。只有 < code > RWO< / code > 时: ①改用对象存储( S3/MinIO) 存图, Pod 只存 URL;
②每个副本挂自己的卷 + 应用层同步(不推荐);③< code > shop-web< / code > 单副本(牺牲可用性)。正确答案是①,
因为图片本来就不该放在容器文件系统里。< / p >
< / details >
< div class = "box tip" >
< span class = "bt" > 延伸挑战( ≤30 分钟)< / span >
< p > 给 < code > postgres-0< / code > 加一个 < code > postgres_exporter< / code > sidecar, 暴露 < code > pg_stat_database< / code >
指标到 9187 端口,先用 < code > kubectl port-forward< / code > 看到 < code > /metrics< / code > 输出即可——第 13 章会把它接进 Prometheus。< / p >
< / div >
< h3 id = "sec-8-12" > 8.12 衔接< / h3 >
< p > < b > 回收< / b > :第 06 章把 < code > DB_HOST< / code > 放进 ConfigMap 时留了一句「地址等有了数据库再填」,本章 Step 4 把它填上了。< / p >
< p > < b > 钩子< / b > :数据现在只在集群内部可达。如果产品经理要求「从公网用 < code > shop.example.com< / code > 打开」,
而集群里连一个公网 IP 都没有,流量该怎么进来?< a href = "09-ingress.html" > 第 9 章< / a > 回答这个问题。< / p >
< h3 id = "sec-8-13" > 8.13 参考与验证版本< / h3 >
< ul >
< li > < a href = "https://kubernetes.io/docs/concepts/storage/persistent-volumes/" > Persistent Volumes< / a > < / li >
< li > < a href = "https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" > StatefulSets< / a > < / li >
< li > < a href = "https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/" > Configure a Pod to Use a PersistentVolume< / a > < / li >
< li > < a href = "https://github.com/rancher/local-path-provisioner" > local-path-provisioner( kind 默认 StorageClass) < / a > < / li >
< / ul >
< p > 验证版本: k8s v1.36 / kubectl v1.36 / postgres:16 · 最后验证: 2026-11-05< / p >
< / article >
< nav class = "pager" >
2026-11-08 15:27:37 +08:00
< a class = "prev" href = "07-probe.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 7 章 · 探针与资源:让它活得像生产< / span > < / a >
2026-11-11 12:33:25 +08:00
< a class = "next" href = "09-ingress.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 9 章 · 入口与网关: Ingress 与 Gateway API< / span > < / a >
2026-11-06 15:52:48 +08:00
< / nav >
< p class = "foot" >
Kubernetes 专题 · S2 第 8 章 存储:从 emptyDir 到 StatefulSet< 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 >