2026-11-08 15:27:37 +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 > 第 3 章 Pod: 最小调度单元 · Kubernetes 专题知识库< / title >
< meta name = "description" content = "把 shop-api 写成源码与镜像,装进一个裸 Pod: 讲清 Pod 为什么是最小调度单元、四个相位与重启策略、镜像拉取策略的默认值、Init 容器与 sidecar 的分工,并用 port-forward 打开首页。" >
< meta name = "keywords" content = "Pod, 最小调度单元, restartPolicy, imagePullPolicy, 相位, Init 容器, sidecar, kind load" >
< 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 > 第 3 章< / 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 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 > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 3< / i > Pod: 最小调度单元< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-3-1" > 3.1 本章在哪:主线之前与之后< / a > < a class = "toc-a lv3" href = "#sec-3-2" > 3.2 学习目标< / a > < a class = "toc-a lv3" href = "#sec-3-3" > 3.3 场景:周一早上,服务没有起来< / a > < a class = "toc-a lv3" href = "#sec-3-4" > 3.4 心智模型:一个 Pod, 一组进程< / a > < a class = "toc-a lv3" href = "#sec-3-5" > 3.5 概念与字段速查< / a > < a class = "toc-a lv3" href = "#sec-3-6" > 3.6 实操:从源码到一个 Running 的 Pod< / a > < a class = "toc-a lv3" href = "#sec-3-7" > 3.7 验收清单< / a > < a class = "toc-a lv3" href = "#sec-3-8" > 3.8 故障实验室< / a > < a class = "toc-a lv3" href = "#sec-3-9" > 3.9 生产对照< / a > < a class = "toc-a lv3" href = "#sec-3-10" > 3.10 清理与残留检查< / a > < a class = "toc-a lv3" href = "#sec-3-11" > 3.11 小结与自测< / a > < a class = "toc-a lv3" href = "#sec-3-12" > 3.12 衔接< / a > < a class = "toc-a lv3" href = "#sec-3-13" > 3.13 参考与验证版本< / a > < / div > < 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 > < 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 > < 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-08 15:27:37 +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 > S1 跑起来:单服务最小闭环< / span >
< span > ·< / span >
< span > 第 < b class = "pos" > 3< / b > / 26 章< / span >
< / p >
< h2 id = "ch3" > < span class = "n" > 3< / span > Pod: 最小调度单元< / h2 >
< div class = "lead" >
< b > 30 秒速览:< / b > < code > shop-api< / code > 现在只活在某个人的终端里。本章把它写成源码与镜像,装进一个叫 Pod 的对象, 让调度器替你选节点、kubelet 替你守进程。做完之后 < code > shop< / code > 里只有一个 Pod, 你能看日志、进容器、把首页转发到本机。约 120 分钟。
< / div >
< h3 id = "sec-3-1" > 3.1 本章在哪:主线之前与之后< / h3 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 项< / th > < th > 内容< / th > < / tr > < / thead >
< tbody >
< tr > < td > 主线之前< / td > < td > < code > shop< / code > 命名空间是空的;< code > shop-api< / code > 的「怎么跑」写在交接文档的一行 < code > nohup< / code > 里,不在仓库里< / td > < / tr >
< tr > < td > 主线之后< / td > < td > < code > shop< / code > 里 1 个 Pod < code > shop-api< / code > 处于 < code > Running< / code > ;能看日志、进容器、把首页转发到本机;没有 Deployment, 没有 Service< / td > < / tr >
< tr > < td > 本章产物< / td > < td > < code > apps/shop-api/{go.mod,main.go,Dockerfile}< / code > 、< code > deploy/base/shop-api-pod.yaml< / code > 、Makefile 的 < code > image< / code > / < code > load< / code > / < code > verify-ch03< / code > < / td > < / tr >
< tr > < td > 适用环境< / td > < td > ENV-A( Windows 11 + WSL2 + kind) 必做; ENV-C 命令相同,差异只在 Docker 引擎归属与 < code > localhost< / code > 的可达性,见 3.6< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 终点留得很窄:一个裸 Pod, 不自愈、不滚动、没有固定地址。三件事分属第 4、14、5 章。< / p >
< h3 id = "sec-3-2" > 3.2 学习目标< / h3 >
< div class = "box note" >
< span class = "bt" > 学完你能< / span >
< ul >
< li > 能从源码构建镜像并送进节点,判定标准:节点上 < code > crictl images< / code > 有 < code > v1.2.3< / code > < / li >
< li > 能写出一个裸 Pod 清单并让它 < code > Running< / code > ,判定标准:< code > kubectl get pod shop-api -n shop< / code > 的 < code > READY< / code > 是 < code > 1/1< / code > < / li >
< li > 能解释 Pod 与容器的关系,判定标准:说清为什么同 Pod 两个容器不能都监听 8080< / li >
< li > 能用 < code > logs< / code > 、< code > exec< / code > 、< code > port-forward< / code > 观察同一个 Pod, 判定标准: 浏览器打开 < code > localhost:8080< / code > 看到 JSON< / li >
< / ul >
< / div >
< h3 id = "sec-3-3" > 3.3 场景:周一早上,服务没有起来< / h3 >
< p > 周一 09:20, < code > shop-api< / code > 打不开。它跑在运维老张的跳板机上,交接文档只有一行 < code > nohup ./shop-api & < / code > 。< / p >
< p > 机器周五夜里打补丁重启,进程没跟着起来。值班的人试了三次:直接跑,与测试环境抢 8080; 加 < code > --port 9090< / code > ,程序不认;翻出旧二进制,< code > hostname< / code > 属于别的机器。< / p >
< p > 40 分钟后才有人想起问老张。问题不是重启:服务的形状只活在一台机器和一个人的记忆里。< / p >
< div class = "box case" >
< span class = "bt" > 现场< / span >
< p > 09:20 起 < code > shop-api< / code > 不可用, 40 分钟内没人说得清它该跑在哪台机器、监听哪个端口、用哪份配置。< / p >
< / div >
< p > 本章把这段历史从跳板机搬进仓库:一个能被 < code > kubectl get< / code > 看见、被 < code > describe< / code > 读出来的对象。< / p >
< h3 id = "sec-3-4" > 3.4 心智模型:一个 Pod, 一组进程< / h3 >
< figure class = "figure" >
< svg viewBox = "0 0 720 330" role = "img" aria-label = "一个 Pod 内部的两个容器共享网络命名空间,只有显式挂载才共享文件" >
< defs >
< marker id = "a3" 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 = "250" y = "34" width = "220" height = "32" rx = "8" style = "fill:var(--soft);stroke:var(--line)" > < / rect >
< text x = "360" y = "55" text-anchor = "middle" font-size = "13" style = "fill:var(--ink)" > 节点 aurora-worker< / text >
< path d = "M360,66 L360,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3)" > < / path >
< rect x = "100" y = "84" width = "520" height = "212" rx = "12" style = "fill:none;stroke:var(--brand)" stroke-dasharray = "6 5" > < / rect >
< text x = "360" y = "107" text-anchor = "middle" font-size = "13" style = "fill:var(--brand)" > Pod shop-api · IP 10.244.1.7< / text >
< rect x = "124" y = "120" width = "220" height = "60" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "234" y = "144" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 容器 shop-api< / text >
< text x = "234" y = "164" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 监听 :8080< / text >
< rect x = "376" y = "120" width = "220" height = "60" rx = "8" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "486" y = "144" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 容器 sidecar( 可选) < / text >
< text x = "486" y = "164" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 与左边共用 localhost< / text >
< rect x = "124" y = "196" width = "472" height = "34" rx = "7" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "360" y = "218" text-anchor = "middle" font-size = "12" style = "fill:var(--brand)" > 共享 network 命名空间:同一个 IP、同一份端口空间< / text >
< rect x = "124" y = "242" width = "472" height = "34" rx = "7" style = "fill:var(--soft);stroke:var(--line)" > < / rect >
< text x = "360" y = "264" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 共享卷:只有显式挂同一个 volume 才有共享文件< / text >
< text x = "360" y = "320" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 调度器搬的是整个 Pod, 不是单个容器< / text >
< / svg >
< div class = "figcap" > < b > 图 1 ·< / b > 一个 Pod 里哪些东西共享、哪些各管各的,以及调度器到底在搬什么。< / div >
< / figure >
< p > 见图 1: 调度器不认容器, 只认 Pod; 整个 Pod 落到一个节点后 kubelet 才启动容器。同 Pod 共享网络与端口空间,两个都监听 8080 时后起来的那个退出。< / p >
< p > 把它想成集装箱:码头吊装整个箱子,不是箱里的货物。理由只有一个——有些进程必须同机、共用同一个 IP。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · 以为同一 Pod 的容器共享文件< / span >
< p > < b > 现象< / b > : sidecar 写的日志,主容器里 < code > ls /var/log< / code > 什么都没有。< b > 原因< / b > :共享的是网络与 IPC, 不是文件系统。< b > 怎么验证< / b > :两个容器各 < code > ls /tmp< / code > ,内容互不相干。< / p >
< / div >
< p > Pod 里可以放不止一个容器。Init 容器按顺序跑完主容器才开始, sidecar 与主容器同时跑;区别在什么时候跑、谁先退出,第 11 章展开。< / p >
< details >
< summary > 可跳过 · Init 容器到底解决什么问题(点击展开)< / summary >
< p > 它做的是主容器开始之前必须完成的事:等依赖就绪、给共享卷改属主、渲染配置模板。塞进启动脚本就难判断失败在哪步;拆开后 < code > logs -c wait-for-db< / code > 直接指出。< / p >
< / details >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 误解< / th > < th > 事实< / th > < / tr > < / thead >
< tbody >
< tr > < td > Pod 就是容器< / td > < td > Pod 是一到多个容器的外壳;调度、扩缩、删除的单位都是 Pod< / td > < / tr >
< tr > < td > Pod 是台小虚拟机,可以 SSH 进去装东西< / td > < td > 没有 init、没有登录用户; 容器一重启就回到镜像的状态, 装过的东西全丢< / td > < / tr >
< tr > < td > Pod 里的容器自动共享一切< / td > < td > 默认只共享网络与 IPC; 文件、进程表、环境变量都是各自的< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-3-5" > 3.5 概念与字段速查< / h3 >
< p > 本章用到的字段都在表里,第三列是这一章的选择;亲和性、优先级到用得上再查。< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 字段< / th > < th > 默认值< / th > < th > 本章怎么用< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > spec.containers[].image< / code > < / td > < td > 必填< / td > < td > < code > registry.local/aurora/shop-api:v1.2.3< / code > ,不写 < code > latest< / code > < / td > < / tr >
< tr > < td > < code > imagePullPolicy< / code > < / td > < td > tag 不是 < code > latest< / code > 时是 < code > IfNotPresent< / code > < / td > < td > 显式写 < code > IfNotPresent< / code > ,配合 < code > kind load< / code > < / td > < / tr >
< tr > < td > < code > spec.restartPolicy< / code > < / td > < td > < code > Always< / code > < / td > < td > 保持 < code > Always< / code > ,这是故障实验室 2 的前提< / td > < / tr >
< tr > < td > < code > spec.containers[].ports< / code > < / td > < td > 无,只是声明< / td > < td > 写 < code > 8080< / code > , < code > port-forward< / code > 与第 5 章都引用它< / td > < / tr >
< tr > < td > < code > spec.containers[].env< / code > < / td > < td > 无< / td > < td > 5 个业务变量,第 6 章改成 ConfigMap 注入< / td > < / tr >
< tr > < td > < code > spec.containers[].command< / code > < / td > < td > 用镜像的 < code > ENTRYPOINT< / code > < / td > < td > 不覆盖,让镜像自己决定怎么启动< / td > < / tr >
< tr > < td > < code > spec.containers[].resources< / code > < / td > < td > 不设限< / td > < td > 第 7 章补 < code > requests< / code > 与 < code > limits< / code > < / td > < / tr >
< tr > < td > < code > spec.nodeSelector< / code > < / td > < td > 空,调度器自选< / td > < td > 正常不用,故障实验室用它制造 < code > Pending< / code > < / td > < / tr >
< tr > < td > < code > spec.initContainers< / code > < / td > < td > 无< / td > < td > 本章不加,第 11 章才用< / td > < / tr >
< tr > < td > < code > metadata.labels< / code > < / td > < td > 无< / td > < td > 三个 < code > app.kubernetes.io/*< / code > 标签,第 4 章靠它们认领 Pod< / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box warn" >
< span class = "bt" > 易错点 · imagePullPolicy 的默认值不是 Always< / span >
< p > < b > 现象< / b > :刚 build 的新镜像, Pod 里跑的却是十几分钟前的旧版本。< b > 原因< / b > :只有 < code > latest< / code > 或不写 tag 才是 < code > Always< / code > ,其余是 < code > IfNotPresent< / code > ,节点上缓存的同名 tag 被复用。< b > 怎么验证< / b > :看 < code > jsonpath< / code > 里的 < code > imagePullPolicy< / code > ;换镜像请换 tag。< / p >
< / div >
< p > 相位只有四个值,外加节点失联时的 < code > Unknown< / code > 。它描述 Pod 整体;< code > STATUS< / code > 列在相位上又叠了一层原因。< / p >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 相位< / th > < th > 含义< / th > < th > 本章在哪里见到< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > Pending< / code > < / td > < td > 已被接受,但容器还没全部跑起来:等调度、拉镜像、挂卷都算< / td > < td > Step 4 的头几秒,以及 Step 5 全程< / td > < / tr >
< tr > < td > < code > Running< / code > < / td > < td > Pod 已绑定节点,至少一个容器在跑或在重启< / td > < td > 正常态,拿到 1/1 之后< / td > < / tr >
< tr > < td > < code > Succeeded< / code > < / td > < td > 所有容器都以 0 退出,且不会再重启< / td > < td > 只有 < code > restartPolicy: Never< / code > 时才可能出现< / td > < / tr >
< tr > < td > < code > Failed< / code > < / td > < td > 至少一个容器非 0 退出,且不会再重启< / td > < td > 同上,本章不会出现< / td > < / tr >
< / tbody >
< / table >
< / div >
< figure class = "figure" >
< svg viewBox = "0 0 720 250" role = "img" aria-label = "Pod 四个相位之间的迁移,以及容器重启如何让 Pod 停在 Running" >
< defs >
< marker id = "a3b" 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 = "36" y = "76" width = "150" height = "48" rx = "9" style = "fill:var(--warn-bg);stroke:var(--warn-line)" > < / rect >
< text x = "111" y = "105" text-anchor = "middle" font-size = "13" style = "fill:var(--warn)" > Pending< / text >
< rect x = "256" y = "76" width = "150" height = "48" rx = "9" style = "fill:var(--ok-bg);stroke:var(--ok-line)" > < / rect >
< text x = "331" y = "105" text-anchor = "middle" font-size = "13" style = "fill:var(--ok)" > Running< / text >
< rect x = "470" y = "18" width = "170" height = "46" rx = "9" style = "fill:var(--soft);stroke:var(--line)" > < / rect >
< text x = "555" y = "46" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > Succeeded< / text >
< rect x = "470" y = "118" width = "170" height = "46" rx = "9" style = "fill:var(--danger-bg);stroke:var(--danger-line)" > < / rect >
< text x = "555" y = "146" text-anchor = "middle" font-size = "12.5" style = "fill:var(--danger)" > Failed< / text >
< path d = "M186,100 L250,100" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3b)" > < / path >
< text x = "218" y = "90" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 调度 + 拉镜像< / text >
< path d = "M406,94 C430,74 440,66 464,58" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3b)" > < / path >
< text x = "452" y = "42" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 0 退出且不再重启< / text >
< path d = "M406,106 C430,126 440,134 464,142" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3b)" > < / path >
< text x = "452" y = "176" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 非 0 退出且不再重启< / text >
< path d = "M306,76 C306,30 140,30 140,70" style = "stroke:var(--brand);fill:none" stroke-dasharray = "5 4" marker-end = "url(#a3b)" > < / path >
< text x = "228" y = "24" text-anchor = "middle" font-size = "11" style = "fill:var(--brand)" > 容器退出后按 restartPolicy 决定是否重开< / text >
< text x = "360" y = "214" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > ContainerCreating、ImagePullBackOff 都还停在 Pending< / text >
< text x = "360" y = "236" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > CrashLoopBackOff 仍算 Running, 只是容器在反复退出< / text >
< / svg >
< div class = "figcap" > < b > 图 2 ·< / b > 相位会往哪里走,以及为什么 < code > STATUS< / code > 列的取值比相位多得多。< / div >
< / figure >
< p > 见图 2: 容器退出后的去向由 < code > restartPolicy< / code > 决定。策略是 < code > Always< / code > 时 Pod 永远进不了 < code > Succeeded< / code > 或 < code > Failed< / code > ,只在 < code > Running< / code > 里反复重启,退避 10 秒起、5 分钟封顶。< / p >
< div class = "box warn" >
< span class = "bt" > 易错点 · Running 不等于能服务< / span >
< p > < b > 现象< / b > : < code > get pods< / code > 显示 < code > Running< / code > ,首页却返回 503。< b > 原因< / b > :相位只表示进程存在,不表示能接流量。< b > 怎么验证< / b > : < code > curl -i localhost:8080/readyz< / code > 看状态码,别只看 < code > STATUS< / code > 。< / p >
< / div >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 取值< / th > < th > 容器退出之后< / th > < th > 谁会用< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > Always< / code > < / td > < td > 总是重启,退避 10 秒起、5 分钟封顶< / td > < td > 长期运行的服务,本章用它< / td > < / tr >
< tr > < td > < code > OnFailure< / code > < / td > < td > 非 0 退出才重启, 0 退出就此结束< / td > < td > 一次性任务,失败要重试< / td > < / tr >
< tr > < td > < code > Never< / code > < / td > < td > 任何退出都不重启< / td > < td > 一次性任务,失败要留现场< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-3-6" > 3.6 实操:从源码到一个 Running 的 Pod< / h3 >
< p > 工作目录固定在 < code > ~/work/aurora-shop< / code > 。八步,每步结束在一个 < code > kubectl get< / code > 可见的状态。< / p >
< h4 > Step 1 · 确认第 2 章的现场还在< / h4 >
< p > < span class = "tag" > 意图< / span > 动源码之前先确认地基: context 是 < code > kind-aurora< / code > , < code > shop< / code > 带标签。< / p >
< pre data-lang = "bash" data-name = "确认现场" > # env: all
export NS=shop
kubectl config current-context
kubectl get ns $NS --show-labels< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
kind-aurora
NAME STATUS AGE LABELS
shop Active 3d app.kubernetes.io/name=shop,app.kubernetes.io/part-of=aurora-shop< / pre >
< p > < b > 不一致怎么办< / b > : context 不对就 < code > kubectl config use-context kind-aurora< / code > ; < code > shop< / code > 不存在就 < code > kubectl apply -f deploy/base/namespace.yaml< / code > 。< / p >
< h4 > Step 2 · 把 APP 写成源码与镜像< / h4 >
< p > < span class = "tag" > 意图< / span > 让「怎么跑」第一次进仓库:四个文件加一个 make 目标,谁跑都得到同一个镜像。< / p >
< pre data-lang = "text" data-name = "apps/shop-api/go.mod" > # file: apps/shop-api/go.mod
module aurora.local/shop-api
go 1.24< / pre >
< pre data-lang = "go" data-name = "apps/shop-api/main.go" > # file: apps/shop-api/main.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime"
"strconv"
"sync/atomic"
"time"
)
var (
version = "dev"
started = time.Now()
requests atomic.Int64
burned atomic.Int64
)
type homepage struct {
Hostname string `json:"hostname"`
Version string `json:"version"`
AppMode string `json:"app_mode"`
Theme string `json:"theme"`
StartedAt string `json:"started_at"`
}
func env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
requests.Add(1)
host, _ := os.Hostname()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(homepage{
Hostname: host,
Version: version,
AppMode: env("APP_MODE", "dev"),
Theme: env("THEME", "light"),
StartedAt: started.Format(time.RFC3339),
})
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "ok")
})
// 启动后的前 3 秒返回 503, 给第 7 章的 readinessProbe 留出可观察的窗口
mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
if time.Since(started) < 3*time.Second {
http.Error(w, "warming up", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "ready")
})
mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
fmt.Fprintf(w, "# TYPE shop_api_requests_total counter\n")
fmt.Fprintf(w, "shop_api_requests_total %d\n", requests.Load())
fmt.Fprintf(w, "# TYPE shop_api_uptime_seconds gauge\n")
fmt.Fprintf(w, "shop_api_uptime_seconds %d\n", int64(time.Since(started).Seconds()))
fmt.Fprintf(w, "# TYPE shop_api_burned_mb_total counter\n")
fmt.Fprintf(w, "shop_api_burned_mb_total %d\n", burned.Load())
})
// 故意吃掉内存,第 7 章用它制造 OOMKilled
mux.HandleFunc("/burn", func(w http.ResponseWriter, r *http.Request) {
mb, err := strconv.Atoi(r.URL.Query().Get("mb"))
if err != nil || mb < 1 {
http.Error(w, "mb must be a positive integer", http.StatusBadRequest)
return
}
keep := make([][]byte, 0, mb)
for i := 0; i < mb; i++ {
keep = append(keep, make([]byte, 1024*1024))
}
burned.Add(int64(mb))
runtime.KeepAlive(keep)
fmt.Fprintf(w, "burned %d MiB\n", mb)
})
// 故障实验室 2 用它观察 CrashLoopBackOff
mux.HandleFunc("/exit", func(w http.ResponseWriter, r *http.Request) {
log.Printf("exit requested by %s", r.RemoteAddr)
os.Exit(1)
})
log.Printf("shop-api %s listening on :8080 mode=%s theme=%s",
version, env("APP_MODE", "dev"), env("THEME", "light"))
log.Fatal(http.ListenAndServe(":8080", mux))
}< / pre >
< p > 六个路由各有用处:< code > /metrics< / code > 留给第 12 章、< code > /burn< / code > 留给第 7 章、< code > /exit< / code > 留给本章的故障实验室。< / p >
< pre data-lang = "dockerfile" data-name = "apps/shop-api/Dockerfile" > # file: apps/shop-api/Dockerfile
FROM golang:1.24-alpine AS build
ARG VERSION=dev
WORKDIR /src
COPY go.mod ./
COPY main.go ./
RUN CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X main.version=${VERSION}" \
-o /out/shop-api .
FROM alpine:3.20
RUN adduser -D -u 10001 app
COPY --from=build /out/shop-api /usr/local/bin/shop-api
USER 10001
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/shop-api"]< / pre >
< p > 两处刻意选择:用 < code > alpine< / code > 而非 < code > distroless< / code > ,因为你要能 < code > exec< / code > 看现场;以 uid 10001 运行,因为第 14 章的安全基线会拒掉 root。版本号经 < code > -ldflags< / code > 注入,镜像 tag 与首页 < code > version< / code > 一致。< / p >
< pre data-lang = "bash" data-name = "Makefile 的 image 目标" > # file: Makefile
# 追加到第 1 章 Makefile 末尾;这里的缩进是 tab, 不是空格
# CLUSTER 与 up/down 都是第 1 章已有的目标
VERSION ?= v1.2.3
IMAGE_API := registry.local/aurora/shop-api:$(VERSION)
image: ## 构建 shop-api 镜像
docker build --build-arg VERSION=$(VERSION) -t $(IMAGE_API) apps/shop-api
@echo "[ok] 镜像 $(IMAGE_API)"
load: image ## 把镜像送进 kind 的三台节点
kind load docker-image $(IMAGE_API) --name $(CLUSTER)
@echo "[ok] 镜像已进入 $(CLUSTER)"
verify-ch03: ## 第 3 章验收:一个 Ready 的裸 Pod
@kubectl get pod shop-api -n shop -o jsonpath='{.status.phase}' | grep -qx Running \
|| { echo "[fail] shop-api 不在 Running"; exit 1; }
@kubectl get pod shop-api -n shop -o jsonpath='{.status.containerStatuses[0].ready}' | grep -qx true \
|| { echo "[fail] 容器未 Ready"; exit 1; }
@echo "[ok] pod shop-api ready 1/1"
@kubectl get pod shop-api -n shop -o jsonpath='{.spec.containers[0].image}' \
| grep -qx 'registry.local/aurora/shop-api:v1.2.3' \
|| { echo "[fail] 镜像不是 v1.2.3"; exit 1; }
@echo "[ok] image registry.local/aurora/shop-api:v1.2.3"
@kubectl get pod shop-api -n shop -o jsonpath='{.spec.restartPolicy}' | grep -qx Always \
|| { echo "[fail] restartPolicy 不是 Always"; exit 1; }
@echo "[ok] restartPolicy Always"
@test -z "$$(kubectl get deploy,svc -n shop -o name)" \
|| { echo "[fail] shop 里出现了 Deployment 或 Service"; exit 1; }
@echo "[ok] 0 个 Deployment、0 个 Service"
@kubectl exec -n shop shop-api -- wget -qO- http://127.0.0.1:8080/healthz | grep -qx ok \
|| { echo "[fail] /healthz 不通"; exit 1; }
@echo "[ok] GET /healthz 200"
< / pre >
< pre data-lang = "bash" data-name = "构建镜像" > # env: all
cd ~/work/aurora-shop
make image< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
docker build --build-arg VERSION=v1.2.3 -t registry.local/aurora/shop-api:v1.2.3 apps/shop-api
[+] Building 21.4s (12/12) FINISHED
=> [build 4/5] RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=v1.2.3"
=> => naming to registry.local/aurora/shop-api:v1.2.3
[ok] 镜像 registry.local/aurora/shop-api:v1.2.3< / pre >
< p > < b > 不一致怎么办< / b > :卡在 < code > go build< / code > ,先在本机 < code > go build ./...< / code > 复现,与镜像分层无关。< / p >
< h4 > Step 3 · 把镜像送进节点< / h4 >
< p > < span class = "tag" > 意图< / span > 让三台 kind 节点真能看到这个镜像。Docker 的镜像仓与节点 containerd 是两个仓, kubelet 只看后者。< / p >
< pre data-lang = "bash" data-name = "kind load" > # env: all
cd ~/work/aurora-shop
make load
docker exec aurora-worker crictl images | grep shop-api< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
kind load docker-image registry.local/aurora/shop-api:v1.2.3 --name aurora
Image: "registry.local/aurora/shop-api:v1.2.3" with ID "sha256:6f0c1b2d9a4e" not yet present on node "aurora-worker2", loading...
Image: "registry.local/aurora/shop-api:v1.2.3" with ID "sha256:6f0c1b2d9a4e" not yet present on node "aurora-worker", loading...
[ok] 镜像已进入 aurora
registry.local/aurora/shop-api v1.2.3 6f0c1b2d9a4e 18.2MB< / pre >
< div class = "grid2" >
< div class = "box" >
< span class = "bt" > Windows 11 + WSL2< / span >
< p > < code > docker< / code > 连的是 Docker Desktop 的引擎,镜像存在 Windows 那边;< code > kind load< / code > 用 < code > docker save< / code > 把 tar 灌进节点 containerd。中转站与终点是两处, < code > docker images< / code > 有、节点里没有是常态。< / p >
< / div >
< div class = "box" >
< span class = "bt" > Linux (Ubuntu 24.04)< / span >
< p > < code > docker< / code > 连本机 < code > dockerd< / code > , < code > docker save< / code > 走本机磁盘;用 rootless docker 或 podman 要先 < code > export KIND_EXPERIMENTAL_PROVIDER=podman< / code > ,否则 < code > kind load< / code > 找不到引擎。< / p >
< / div >
< / div >
< p > < b > 差异结论< / b > :两条路都止于节点 containerd; 区别只在 Docker 跑在哪个内核上。< / p >
< p > < b > 不一致怎么办< / b > : < code > [ok]< / code > 没出现,多半是集群名写错或 Docker 没起来。< / p >
< h4 > Step 4 · 写清单,让它 Running< / h4 >
< p > < span class = "tag" > 意图< / span > 第一次用 < code > kubectl apply< / code > 提交工作负载。清单里显式写 < code > namespace< / code > ,不依赖 < code > -n< / code > 的默认值。< / p >
< pre data-lang = "yaml" data-name = "deploy/base/shop-api-pod.yaml" > # file: deploy/base/shop-api-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: shop-api
namespace: shop
labels:
app.kubernetes.io/name: shop-api
app.kubernetes.io/instance: shop
app.kubernetes.io/version: v1.2.3
app.kubernetes.io/part-of: aurora-shop
spec:
restartPolicy: Always
containers:
- name: shop-api
image: registry.local/aurora/shop-api:v1.2.3
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 8080
env:
- name: APP_MODE
value: dev
- name: THEME
value: light
- name: FEATURE_NEW_CHECKOUT
value: "false"
- name: LOG_LEVEL
value: info
- name: DATABASE_URL
value: postgres://shop:shop@postgres.shop.svc.cluster.local:5432/shop< / pre >
< p > < code > DATABASE_URL< / code > 指向一个还不存在的 Service: 进程不拨号, 要到第 8 章才有意义。< / p >
< pre data-lang = "bash" data-name = "apply 并观察相位" > # env: all
export NS=shop
kubectl apply -f deploy/base/shop-api-pod.yaml
kubectl get pod shop-api -n $NS -o wide< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
pod/shop-api created
NAME READY STATUS RESTARTS AGE IP NODE
shop-api 1/1 Running 0 9s 10.244.1.7 aurora-worker< / pre >
< details >
< summary > 可跳过 · 这份清单为什么没有 resources 和探针(点击展开)< / summary >
< p > 探针与 < code > requests< / code > 都在第 07 章补齐。现在加上也能跑,但你会同时面对探针失败与资源不足两种报错,排障顺序就乱了。< / p >
< / details >
< p > < b > 不一致怎么办< / b > :卡在 < code > ContainerCreating< / code > 超过一分钟,先 < code > describe< / code > 看 Events, 再回 Step 3。< / p >
< h4 > Step 5 · 负向步骤:先让它拉不到镜像< / h4 >
< p > < span class = "tag" > 意图< / span > 亲手制造一次 < code > ErrImagePull< / code > 。见过了,在别人的集群里看到才不会慌。< / p >
< pre data-lang = "bash" data-name = "改成一个不存在的 tag" > # env: all
export NS=shop
kubectl set image pod/shop-api -n $NS shop-api=registry.local/aurora/shop-api:v1.2.4
sleep 20
kubectl get pod shop-api -n $NS< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
pod/shop-api image updated
NAME READY STATUS RESTARTS AGE
shop-api 0/1 ImagePullBackOff 0 4m< / pre >
< pre data-lang = "bash" data-name = "看 Events 里的真实报错" > # env: all
export NS=shop
kubectl describe pod shop-api -n $NS | sed -n '/Events:/,$p'< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 4m12s default-scheduler Successfully assigned shop/shop-api to aurora-worker
Normal Pulled 4m10s kubelet Container image already present on machine
Warning Failed 70s (x2 over 100s) kubelet Failed to pull image "registry.local/aurora/shop-api:v1.2.4":
dial tcp: lookup registry.local on 10.96.0.10:53: no such host
Warning Failed 70s (x2 over 100s) kubelet Error: ErrImagePull
Normal BackOff 40s (x5 over 95s) kubelet Back-off pulling image "registry.local/aurora/shop-api:v1.2.4"< / pre >
< p > < code > STATUS< / code > 已是 < code > ImagePullBackOff< / code > ,相位却仍是 < code > Pending< / code > :镜像没拉下来,容器就没开始跑,见图 2。< / p >
< pre data-lang = "bash" data-name = "改回正确的 tag" > # env: all
export NS=shop
kubectl set image pod/shop-api -n $NS shop-api=registry.local/aurora/shop-api:v1.2.3
kubectl wait --for=condition=Ready pod/shop-api -n $NS --timeout=90s< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
pod/shop-api image updated
pod/shop-api condition met< / pre >
< div class = "box warn" >
< span class = "bt" > 易错点 · 想用 kubectl edit 改 command< / span >
< p > < b > 现象< / b > :改完 < code > command< / code > 保存,报 < code > The Pod "shop-api" is invalid: spec: Forbidden: pod updates may not change fields other than spec.containers[*].image, spec.initContainers[*].image, spec.activeDeadlineSeconds, spec.tolerations< / code > 。< b > 原因< / b > :容器模板不可变,只有 < code > image< / code > 、< code > activeDeadlineSeconds< / code > 、追加 < code > tolerations< / code > 这类少数字段能原地更新。< b > 怎么验证< / b > : < code > kubectl get pod shop-api -n shop -o jsonpath='{.spec.containers[0].command}'< / code > ,值没变就是没生效;正确做法是改 YAML 后删掉重建。< / p >
< / div >
< p > < b > 不一致怎么办< / b > :没进 < code > ImagePullBackOff< / code > ,说明节点上真有同名 tag, 换一个不存在的 tag。< / p >
< h4 > Step 6 · 看日志,进容器,再挂一个调试容器< / h4 >
< p > < span class = "tag" > 意图< / span > 分清三种观察方式:< code > logs< / code > 看进程说了什么,< code > exec< / code > 看容器里有什么,< code > debug< / code > 在连 < code > sh< / code > 都没有的镜像里也能进。< / p >
< pre data-lang = "bash" data-name = "日志与容器内自检" > # env: all
export NS=shop
kubectl logs -n $NS shop-api --tail=5
kubectl exec -n $NS shop-api -- wget -qO- http://127.0.0.1:8080/healthz< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
2026/11/08 09:12:41 shop-api v1.2.3 listening on :8080 mode=dev theme=light
ok< / pre >
< p > 日志只有一行,因为进程还没被打扰过。镜像基于 < code > alpine< / code > , < code > sh< / code > 与 < code > wget< / code > 都在;换成 < code > distroless< / code > 就只能走上面的 < code > debug< / code > 。< / p >
< pre data-lang = "bash" data-name = "挂一个临时容器" > # env: all
export NS=shop
kubectl debug -n $NS -it pod/shop-api --image=busybox:1.36 --target=shop-api -- sh< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
Defaulting debug container name to debugger-7k2qp.
If you do not see a command prompt, try pressing enter.
/ # ps
PID USER TIME COMMAND
1 10001 0:00 /usr/local/bin/shop-api
14 root 0:00 sh< / pre >
< p > < code > --target< / code > 让调试容器借用目标的进程命名空间,< code > ps< / code > 看到的 pid 1 就是 < code > shop-api< / code > 。退出后 < code > ephemeralContainers< / code > 还留着记录,只随 Pod 重建消失。< / p >
< p > < b > 不一致怎么办< / b > :容器里没有 < code > wget< / code > ,说明基础镜像不是 < code > alpine< / code > ,改用下面的 < code > debug< / code > 。< / p >
< h4 > Step 7 · 把 8080 转发到本机< / h4 >
< p > < span class = "tag" > 意图< / span > 在没有 Service 和 Ingress 的阶段先让浏览器打开首页。< code > port-forward< / code > 走 apiserver 隧道,不是网络方案。< / p >
< pre data-lang = "bash" data-name = "前台转发" > # env: all
export NS=shop
kubectl port-forward -n $NS pod/shop-api 8080:8080< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
Handling connection for 8080< / pre >
< p > 另开终端访问首页,不依赖浏览器:< / p >
< pre data-lang = "bash" data-name = "验证首页" > # env: all
curl -s localhost:8080/< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
{"hostname":"shop-api","version":"v1.2.3","app_mode":"dev","theme":"light","started_at":"2026-11-08T09:12:41+08:00"}< / pre >
< p > < code > hostname< / code > 是 < code > shop-api< / code > 而不是节点名:它默认取 < code > metadata.name< / code > ,这是 Pod 与「机器」最直观的区别。< / p >
< div class = "grid2" >
< div class = "box" >
< span class = "bt" > Windows 11 + WSL2< / span >
< p > < code > port-forward< / code > 只监听 WSL 的 < code > 127.0.0.1< / code > ; Windows 浏览器访问 < code > http://localhost:8080< / code > 通常可用( WSL2 会转发 localhost) , 失效时加 < code > --address 0.0.0.0< / code > 并用 < code > hostname -I< / code > 拿到的 WSL 地址。< / p >
< / div >
< div class = "box" >
< span class = "bt" > Linux (Ubuntu 24.04)< / span >
< p > 浏览器与 < code > kubectl< / code > 在同一个网络命名空间,< code > localhost:8080< / code > 直接可用;要放给同网段其他机器访问才加 < code > --address 0.0.0.0< / code > ,那等于同网段都能连这条隧道。< / p >
< / div >
< / div >
< p > < b > 差异结论< / b > :默认都只监听回环,区别在 WSL2 多一层 localhost 转发;打不开先在 WSL 内 < code > curl< / code > ,通就是浏览器那侧的事。< / p >
< p > < b > 不一致怎么办< / b > : < code > curl< / code > 通而浏览器不通,问题在 localhost 转发那一层,不是 Pod。< / p >
< h4 > Step 8 · 验收并提交< / h4 >
< p > < span class = "tag" > 意图< / span > 把「本章做完了」变成一条可重复执行的命令,然后提交这批文件。< / p >
< pre data-lang = "bash" data-name = "跑验收并提交" > # env: all
cd ~/work/aurora-shop
make verify-ch03
git add apps/shop-api deploy/base/shop-api-pod.yaml Makefile
git commit -m "ch03: shop-api 源码、镜像与单 Pod 清单"< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
[ok] pod shop-api ready 1/1
[ok] image registry.local/aurora/shop-api:v1.2.3
[ok] restartPolicy Always
[ok] 0 个 Deployment、0 个 Service
[ok] GET /healthz 200
[main 3f1c9a2] ch03: shop-api 源码、镜像与单 Pod 清单
5 files changed, 214 insertions(+)< / pre >
< p > < b > 不一致怎么办< / b > :断言都带 < code > [fail]< / code > 前缀,指向哪个字段就回哪一节查;< code > /healthz< / code > 不通先确认 < code > port-forward< / code > 还开着。< / p >
< p class = "take" > < b > 一句话:< / b > Pod 跑起来只证明进程在,打开页面才证明它是服务。< / p >
< h3 id = "sec-3-7" > 3.7 验收清单< / h3 >
< p > 前四条对应 3.2 的四条目标,第五条是反向验证,末尾那条命令是机器判卷。< / p >
< ol class = "steps" >
< li > < code > kubectl get pod shop-api -n shop< / code > 的 < code > READY< / code > 为 < code > 1/1< / code > , < code > STATUS< / code > 为 < code > Running< / code > < / li >
< li > < code > docker exec aurora-worker crictl images | grep shop-api< / code > 能看到 < code > v1.2.3< / code > ,证明镜像真的进了节点< / li >
< li > 能说清「两个容器不能都监听 8080」的原因: 同一 Pod 共享网络命名空间与端口空间< / li >
< li > < code > curl -s localhost:8080/< / code > 返回包含 < code > "version":"v1.2.3"< / code > 的 JSON< / li >
< li > 反向验证:< code > kubectl get deploy,svc,rs -n shop< / code > 应输出 < code > No resources found< / code > ,出现任何一种都说明你提前做了第 4 或第 5 章的事< / li >
< / ol >
< pre data-lang = "bash" data-name = "机器判卷" > # env: all
cd ~/work/aurora-shop
make verify-ch03< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
[ok] pod shop-api ready 1/1
[ok] image registry.local/aurora/shop-api:v1.2.3
[ok] restartPolicy Always
[ok] 0 个 Deployment、0 个 Service
[ok] GET /healthz 200< / pre >
< h3 id = "sec-3-8" > 3.8 故障实验室< / h3 >
< p > 三个故障都能复现,注入动作都能撤回。顺序见图 3: 看 < code > STATUS< / code > 决定去哪一支,再看 Events 与日志。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 250" role = "img" aria-label = "按 kubectl get pods 的 STATUS 分流到四条诊断路径" >
< defs >
< marker id = "a3c" 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 = "250" y = "8" width = "220" height = "38" rx = "9" style = "fill:var(--brand-soft);stroke:var(--brand)" > < / rect >
< text x = "360" y = "32" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand)" > kubectl get pods 看 STATUS< / text >
< path d = "M360,46 L360,64" style = "stroke:var(--muted);fill:none" > < / path >
< path d = "M97,64 L601,64" style = "stroke:var(--muted);fill:none" > < / path >
< path d = "M97,64 L97,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3c)" > < / path >
< path d = "M265,64 L265,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3c)" > < / path >
< path d = "M433,64 L433,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3c)" > < / path >
< path d = "M601,64 L601,80" style = "stroke:var(--muted);fill:none" marker-end = "url(#a3c)" > < / path >
< rect x = "22" y = "84" width = "150" height = "104" rx = "9" style = "fill:var(--warn-bg);stroke:var(--warn-line)" > < / rect >
< text x = "97" y = "106" text-anchor = "middle" font-size = "12" style = "fill:var(--warn)" > Pending< / text >
< text x = "97" y = "128" text-anchor = "middle" font-size = "11" style = "fill:var(--ink)" > describe 看 Events< / text >
< text x = "97" y = "148" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 资源不足 / 污点< / text >
< text x = "97" y = "168" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 实验室 1< / text >
< rect x = "190" y = "84" width = "150" height = "104" rx = "9" style = "fill:var(--danger-bg);stroke:var(--danger-line)" > < / rect >
< text x = "265" y = "106" text-anchor = "middle" font-size = "12" style = "fill:var(--danger)" > ImagePullBackOff< / text >
< text x = "265" y = "128" text-anchor = "middle" font-size = "11" style = "fill:var(--ink)" > describe 找 Failed< / text >
< text x = "265" y = "148" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > tag 写错 / 没 load< / text >
< text x = "265" y = "168" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > Step 5< / text >
< rect x = "358" y = "84" width = "150" height = "104" rx = "9" style = "fill:var(--danger-bg);stroke:var(--danger-line)" > < / rect >
< text x = "433" y = "106" text-anchor = "middle" font-size = "12" style = "fill:var(--danger)" > CrashLoopBackOff< / text >
< text x = "433" y = "128" text-anchor = "middle" font-size = "11" style = "fill:var(--ink)" > logs --previous< / text >
< text x = "433" y = "148" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 退出码与最后一行< / text >
< text x = "433" y = "168" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 实验室 2< / text >
< rect x = "526" y = "84" width = "150" height = "104" rx = "9" style = "fill:var(--card);stroke:var(--line)" > < / rect >
< text x = "601" y = "106" text-anchor = "middle" font-size = "12" style = "fill:var(--ink)" > Running 但打不开< / text >
< text x = "601" y = "128" text-anchor = "middle" font-size = "11" style = "fill:var(--ink)" > exec 里 wget 自查< / text >
< text x = "601" y = "148" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > 监听地址与端口< / text >
< text x = "601" y = "168" text-anchor = "middle" font-size = "11" style = "fill:var(--muted)" > port-forward 那一层< / text >
< text x = "360" y = "222" text-anchor = "middle" font-size = "11.5" style = "fill:var(--muted)" > 排在最后的才是网络:容器内能通的,别去查 Service< / text >
< / svg >
< div class = "figcap" > < b > 图 3 ·< / b > 看到 < code > STATUS< / code > 之后的四条分支,每条分支的第一个命令都不同。< / div >
< / figure >
< div class = "box danger" >
< span class = "bt" > 故障 1 · Pod 一直 Pending, Events 里是 FailedScheduling< / span >
< p > < b > 注入< / b > :给清单加一段 < code > resources.requests.cpu: "8"< / code > ,重新 apply。< / p >
< p > < b > 症状< / b > : < code > STATUS< / code > 停在 < code > Pending< / code > , < code > READY 0/1< / code > ,节点上没有容器被创建。< / p >
< p > < b > 诊断< / b > : < code > kubectl describe pod shop-api -n shop< / code > , Events 最后一行是 < code > 0/3 nodes are available: 3 Insufficient cpu< / code > 。< / p >
< p > < b > 根因< / b > :调度器按 < code > requests< / code > 找节点,三台 kind 节点各 2 核, 8 核永远排不上。< / p >
< p > < b > 修复< / b > :把 < code > requests< / code > 改成 < code > 100m< / code > 后重新 apply; Pod 已存在时先 < code > delete< / code > ,因为容器模板不可变。< / p >
< p > < b > 预防< / b > : < code > requests< / code > 按压测结果给,别按「反正够用」估。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 2 · 容器启动即退出, CrashLoopBackOff< / span >
< p > < b > 注入< / b > : < code > kubectl exec -n shop shop-api -- wget -qO- http://127.0.0.1:8080/exit< / code > 。< / p >
< p > < b > 症状< / b > : < code > STATUS< / code > 变成 < code > CrashLoopBackOff< / code > , < code > RESTARTS< / code > 一路涨,< code > logs< / code > 里只剩最后一行。< / p >
< p > < b > 诊断< / b > : < code > kubectl logs shop-api -n shop --previous< / code > 看到 < code > exit requested by 127.0.0.1:41234< / code > , < code > kubectl describe< / code > 里 < code > Last State: Terminated, Exit Code: 1< / code > 。< / p >
< p > < b > 根因< / b > :进程以 1 退出,< code > restartPolicy: Always< / code > 要求 kubelet 重开,重开又立刻退出,退避逐步翻倍。< / p >
< p > < b > 修复< / b > :会自愈,等退避结束;不想等就 < code > delete< / code > 后重新 apply。日志若空, 说明容器没跑起来, 改看 Events 里的 < code > exec< / code > 报错。< / p >
< p > < b > 预防< / b > : < code > /exit< / code > 不能留在对外可达的进程里;启动失败看 Events, 运行中崩溃看 < code > --previous< / code > 日志。< / p >
< / div >
< div class = "box danger" >
< span class = "bt" > 故障 3 · 删掉 Pod 之后,它没有回来< / span >
< p > < b > 注入< / b > : < code > kubectl delete pod shop-api -n shop< / code > ,删掉这个 Pod。< / p >
< p > < b > 症状< / b > : < code > kubectl get pods -n shop< / code > 输出 < code > No resources found< / code > ,等十分钟也没有新 Pod。< / p >
< p > < b > 诊断< / b > : < code > kubectl get pod shop-api -n shop -o jsonpath='{.metadata.ownerReferences}'< / code > 返回空,说明它没有主人。< / p >
< p > < b > 根因< / b > :裸 Pod 没有控制器。删除、节点失联、机器腾退,都没有组件负责补一个新的。< / p >
< p > < b > 修复< / b > :重新 < code > kubectl apply -f deploy/base/shop-api-pod.yaml< / code > , IP 会变,其他照旧。< / p >
< p > < b > 预防< / b > :集群内无解,这是第 4 章存在的全部理由——把 Pod 交给控制器,让「期望 1 个」被持续比对。< / p >
< / div >
< h3 id = "sec-3-9" > 3.9 生产对照< / h3 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > 学习环境< / th > < th > 生产环境< / th > < th > 为什么不同< / th > < th > 迁移动作< / th > < / tr > < / thead >
< tbody >
< tr > < td > 清单形态< / td > < td > 一个裸 Pod< / td > < td > Deployment 或 StatefulSet 管 Pod< / td > < td > 裸 Pod 不自愈、不能滚动、不能扩缩< / td > < td > 第 4 章把模板搬进 Deployment< / td > < / tr >
< tr > < td > 镜像来源< / td > < td > < code > kind load< / code > 塞进节点< / td > < td > 私有 registry + 拉取凭据< / td > < td > 节点是几百台而不是三台,没法逐台 load< / td > < td > 换仓库地址,加 < code > imagePullSecrets< / code > < / td > < / tr >
< tr > < td > 镜像 tag< / td > < td > 手写 < code > v1.2.3< / code > < / td > < td > Git SHA 或构建号,不可变< / td > < td > 要能回答「线上跑的是哪个 commit」< / td > < td > CI 里用 < code > --build-arg VERSION=$(git rev-parse --short HEAD)< / code > < / td > < / tr >
< tr > < td > 资源声明< / td > < td > 不写 < code > requests< / code > < / td > < td > 必写 < code > requests< / code > , < code > limits< / code > 谨慎< / td > < td > 没有 < code > requests< / code > ,调度器只能盲排< / td > < td > 第 7 章按压测值补齐< / td > < / tr >
< tr > < td > 变更方式< / td > < td > < code > kubectl set image< / code > 现场改< / td > < td > 改 Git, 走流水线滚动< / td > < td > 现场改的东西查不到、回滚不了< / td > < td > 本章的 < code > set image< / code > 只用于负向实验< / td > < / tr >
< / tbody >
< / table >
< / div >
< h3 id = "sec-3-10" > 3.10 清理与残留检查< / h3 >
< p > 终点是 Pod 还在跑,所以清理只用于「中途做砸了,想回到 Step 4 之前」。< / p >
< pre data-lang = "bash" data-name = "回到本章开始前" > # env: all
export NS=shop
kubectl delete pod shop-api -n $NS --ignore-not-found< / pre >
< pre data-lang = "bash" data-name = "残留检查" > # env: all
export NS=shop
kubectl get pod,deploy,svc,rs -n $NS
kind get clusters
docker images | grep aurora/shop-api< / pre >
< pre data-lang = "text" data-name = "预期输出" > # 预期输出
No resources found in shop namespace.
aurora
registry.local/aurora/shop-api v1.2.3 6f0c1b2d9a4e 18.2MB< / pre >
< p > 镜像留在 Docker 与三台节点的 containerd 里:< code > make down< / code > 时才消失,之后要重新 < code > make load< / code > 。< / p >
< h3 id = "sec-3-11" > 3.11 小结与自测< / h3 >
< p class = "take" > < b > 一句话:< / b > Pod 是最小调度单位,容器只是其中的进程;调度、扩缩、删除都以 Pod 计。< / p >
< p class = "take" > < b > 一句话:< / b > 相位只有四个值;< code > STATUS< / code > 列在相位上叠了原因:看到 < code > ImagePullBackOff< / code > ,相位仍是 < code > Pending< / code > 。< / p >
< p class = "take" > < b > 一句话:< / b > < code > imagePullPolicy< / code > 的默认值由 tag 决定,只有 < code > latest< / code > 或不写 tag 才是 < code > Always< / code > 。< / p >
< p class = "take" > < b > 一句话:< / b > < code > restartPolicy< / code > 管容器退出后要不要重开, 管不了「Pod 会不会被重建」。< / p >
< p class = "take" > < b > 一句话:< / b > 裸 Pod 没有主人:删了就是删了,节点挂了也不搬家。< / p >
< details >
< summary > 自测 3 题(点击展开答案)< / summary >
< p > < b > 1.< / b > 一个 Pod 里两个容器都监听 8080, 会发生什么? < / p >
< p > 后启动的报 < code > bind: address already in use< / code > 退出,按 < code > restartPolicy< / code > 反复重启,最后 < code > CrashLoopBackOff< / code > 。< / p >
< p > < b > 2.< / b > 为什么 < code > kubectl set image< / code > 能改镜像,改 < code > command< / code > 却被拒绝?< / p >
< p > 容器模板不可变,只放开 < code > image< / code > 、< code > activeDeadlineSeconds< / code > 、< code > tolerations< / code > 等字段;换命令只能重建。< / p >
< p > < b > 3.< / b > < code > STATUS=Running< / code > 与 < code > READY 1/1< / code > 有什么区别?< / p >
< p > 前者是 Pod 相位,说明进程在跑;后者是容器 ready 的聚合。本章没有探针, Running 即 1/1; 第 7 章加上探针两者才分开。< / p >
< / details >
< div class = "box tip" >
< span class = "bt" > 延伸挑战( ≤30 分钟)< / span >
< p > 给 < code > shop-api< / code > 加 < code > busybox< / code > sidecar, 两容器挂同一个 < code > emptyDir< / code > , sidecar 每秒写 < code > /shared/tick.log< / code > ,主容器 < code > cat< / code > 到增长即完成。< / p >
< / div >
< h3 id = "sec-3-12" > 3.12 衔接< / h3 >
< p > < b > 回收< / b > :第 2 章留下的「< code > get pods< / code > → < code > get events< / code > → < code > describe< / code > → < code > logs< / code > 」现在有对象可练了。< / p >
< p > < b > 钩子< / b > :这个 Pod 死一次就要人 < code > apply< / code > 一次。要求「同时跑三个」时,你得写三份 YAML、盯三个 IP。< a href = "04-deployment.html" > 第 4 章< / a > 把清单交给控制器,让「三个」变成一个数字。< / p >
< h3 id = "sec-3-13" > 3.13 参考与验证版本< / h3 >
< ul >
< li > < a href = "https://kubernetes.io/docs/concepts/workloads/pods/" > Pods< / a > < / li >
< li > < a href = "https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/" > Pod Lifecycle< / a > < / li >
< li > < a href = "https://kubernetes.io/docs/concepts/containers/images/#image-pull-policy" > Images · Image pull policy< / a > < / li >
< li > < a href = "https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/#ephemeral-container" > Debug Running Pods · Ephemeral containers< / a > < / li >
< li > < a href = "https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.36/#pod-v1-core" > Kubernetes API v1.36 · Pod< / a > < / li >
< / ul >
< p > 验证版本: k8s v1.36.1 / kubectl v1.36.1 / kind v0.30 / Go 1.24 / alpine 3.20 · 最后验证: 2026-11-08< / p >
< / article >
< nav class = "pager" >
< a class = "prev" href = "02-kubectl.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 2 章 · kubectl 与集群解剖:把黑盒变成可观测对象< / span > < / a >
< a class = "next" href = "04-deployment.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 4 章 · Deployment: 副本与滚动更新< / span > < / a >
< / nav >
< p class = "foot" >
Kubernetes 专题 · S1 第 3 章 Pod: 最小调度单元< 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 >