为什么这个 Pod 一直 Pending
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
order-api-0 0/1 Pending 0 5m
kubectl describe pod order-api-0 显示:
Events:
Type Reason From Message
---- ------ ---- -------
Warning FailedScheduling default-scheduler
0/3 nodes are available: 3 Insufficient cpu.
根因:resources.requests.cpu 设成了 2,但节点只剩 1 核可用。
K8s 的调度完全基于 requests,不理解你的应用实际要多少资源。这篇梳理核心对象和资源模型。
Pod:最小的调度单元
为什么是 Pod 而不是容器
Pod 是「一组共享网络和存储的容器」。设计意图:
apiVersion: v1
kind: Pod
metadata:
name: web-app
spec:
containers:
# 主容器:Nginx
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
# Sidecar:日志收集
- name: sidecar-log
image: fluent-bit:1.9
volumeMounts:
- name: logs
mountPath: /var/log/nginx
# 共享网络:两个容器共用同一个 IP 和端口空间
# → localhost:8080 可以直接访问
volumes:
- name: logs
emptyDir: {}
典型组合:
主应用容器 + 日志 sidecar(收集到 stdout)
主应用容器 + 代理 sidecar(Envoy / Istio)
主应用容器 + 监控 sidecar(Prometheus exporter)
Pod 的生命周期
Pending ──调度成功──> Running ──容器全部正常──> Running
│ │
│ ├── 容器退出(非 0)
│ ▼
│ Terminating ──优雅退出超时──> Killed
│ │
│ ├── 优雅退出完成
│ ▼
│ Completed/Succeeded
│
└── 调度失败(资源不足/节点选择器不匹配)──> 一直 Pending
关键点:Pod 是不可变的。改了 spec 就得删掉重建。
Pod 的三个陷阱
陷阱一:Pod IP 会变
$ kubectl get pods
NAME IP
order-api-0 10.244.1.5 # 第一次
$ kubectl delete pod order-api-0
$ kubectl get pods
NAME IP
order-api-0 10.244.2.8 # 变了!
这正是 Service 存在的原因 —— 用稳定的服务名代替 Pod IP。
陷阱二:多副本要靠标签而不是名字
spec:
selector:
matchLabels:
app: order-api
template:
metadata:
labels:
app: order-api # 必须与 selector 匹配
spec:
containers:
- name: order-api
image: order-api:v1.2.0
label 是 K8s 中最重要的概念,几乎所有资源选择都靠它。
陷阱三:重启策略
spec:
restartPolicy: Always # Pod 级别(Deployment 只能是 Always)
容器级别:
containers:
- name: sidecar
restartPolicy: Always # sidecar 特殊:支持 Never(配合原生 sidecar)
labels 与 selectors
标签规范
metadata:
labels:
app: order-api # 应用名
version: v1.2.0 # 版本(K8s 常用 app.kubernetes.io/version)
env: production # 环境
team: backend # 负责团队
tier: backend # 层级
官方推荐的标签前缀:
labels:
app.kubernetes.io/name: order-api
app.kubernetes.io/instance: order-api-prod
app.kubernetes.io/version: "1.2.0"
app.kubernetes.io/component: api
app.kubernetes.io/part-of: shop-system
app.kubernetes.io/managed-by: helm
选择器匹配规则
spec:
selector:
matchLabels: # 精确匹配(AND)
app: order-api
env: production
matchExpressions: # 表达式匹配
- key: tier
operator: In
values: [backend, gateway]
四种操作符:
| 操作符 | 含义 | 示例 |
|---|---|---|
In | 值在列表中 | tier In (backend, gateway) |
NotIn | 值不在列表中 | tier NotIn (frontend) |
Exists | 键存在 | env Exists |
DoesNotExist | 键不存在 | debug DoesNotExist |
Service 的两种 selector
apiVersion: v1
kind: Service
metadata:
name: order-api
spec:
type: ClusterIP
selector:
app: order-api # 精确匹配
ports:
- port: 80
targetPort: 8080
# 或者用表达式做更复杂的匹配
selector:
matchExpressions:
- key: app
operator: In
values: [order-api, order-worker]
注意:Service 的 selector 是等值匹配,不能用表达式(只支持 =、!=)。要复杂匹配要用 matchExpressions,但那是在 Service 的 spec.selector 里不支持的。
结论:Service selector 只能是简单的 key=value。
Deployment:声明式管理
三个核心字段
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-api
spec:
replicas: 3 # 副本数
selector:
matchLabels:
app: order-api
strategy: # 更新策略
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # 最多多出 1 个(总数 4)
maxUnavailable: 0 # 最多不可用 0 个
template: # Pod 模板
metadata:
labels:
app: order-api
spec:
containers:
- name: order-api
image: order-api:v1.2.0
ports:
- containerPort: 8080
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: 1000m
memory: 1Gi
更新策略对比
# 滚动更新:maxUnavailable=0 → 零停机
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
# 流程:起新 Pod → 等就绪 → 删旧 Pod → 起下一个
# 特点:零停机,但资源占用高(需要双倍资源)
# 重建:全部删完再重建
strategy:
type: Recreate
# 特点:资源占用低,但有停机窗口
经验值:
maxSurge=1, maxUnavailable=0 → 生产环境(零停机)
maxSurge=0, maxUnavailable=1 → 资源紧张时(先删后加)
Recreate → 单副本且不要求零停机
回滚
# 查看历史
kubectl rollout history deployment/order-api
# 回滚到上一个版本
kubectl rollout undo deployment/order-api
# 回滚到指定版本
kubectl rollout undo deployment/order-api --to-revision=3
# 实时观察更新
kubectl rollout status deployment/order-api --watch=true
回滚的底层原理:Deployment 保留了旧版本的 ReplicaSet,回滚只是「把副本数切回去」。
Service 详解
四种类型
# ① ClusterIP:集群内部访问(默认)
apiVersion: v1
kind: Service
metadata:
name: order-api-internal
spec:
type: ClusterIP
selector:
app: order-api
ports:
- name: http
port: 80
targetPort: 8080
# 访问:http://order-api-internal:80
# ② NodePort:节点端口直连(30000-32767)
apiVersion: v1
kind: Service
metadata:
name: order-api-nodeport
spec:
type: NodePort
selector:
app: order-api
ports:
- port: 80
targetPort: 8080
nodePort: 30080
# 访问:http://<任一节点IP>:30080
# ⚠️ 生产环境不要直接暴露 NodePort
# ③ LoadBalancer:云厂商负载均衡
apiVersion: v1
kind: Service
metadata:
name: order-api-lb
spec:
type: LoadBalancer
selector:
app: order-api
ports:
- port: 80
targetPort: 8080
# 阿里云会创建 SLB,会产生费用
# ④ ExternalName:DNS 指向(不创建代理)
apiVersion: v1
kind: Service
metadata:
name: external-db
spec:
type: ExternalName
externalName: mysql.default.svc.cluster.local
生产推荐架构:
外部请求
↓
Ingress / Gateway(TLS 终止、域名路由)
↓
Service (ClusterIP)
↓
Deployment → Pod(多个副本)
会话保持
spec:
sessionAffinity: ClientIP # 按客户端 IP 固定
sessionAffinityConfig:
clientIP:
timeoutSeconds: 10800 # 3 小时
什么时候需要会话保持:
✓ 应用完全无状态 → 不需要
△ 单例缓存(如 Vuex 服务端)→ 需要,或改用 Redis
✗ 有状态的业务逻辑 → 这是设计问题,不是 K8s 能解决的
更好的做法:把状态外置到 Redis,然后去掉会话保持。
常用 DNS 解析
# 同 Service 内的 Pod
order-api-0.order-api.default.svc.cluster.local
# 不同 Service 之间(简写)
order-api.default # 同 namespace
order-api.other-ns # 跨 namespace
order-api.other-ns.svc # 完整形式
Ingress:入口路由
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop-ingress
annotations:
nginx.ingress.kubernetes.io/proxy-body-size: "10m"
nginx.ingress.kubernetes.io/proxy-connect-timeout: "5"
nginx.ingress.kubernetes.io/proxy-read-timeout: "60"
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
ingressClassName: nginx
tls:
- hosts:
- shop.example.com
- api.example.com
secretName: shop-tls-secret
rules:
# 规则 1:主域名
- host: shop.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-frontend
port:
number: 80
# 规则 2:API 子域名(host 不同则规则独立)
- host: api.example.com
http:
paths:
- path: /order
pathType: Prefix
backend:
service:
name: order-api
port:
number: 80
- path: /user
pathType: Prefix
backend:
service:
name: user-api
port:
number: 80
pathType 的三种取值:
| 类型 | 匹配规则 | 说明 |
|---|---|---|
Exact | 精确匹配 | /api 只匹配 /api |
Prefix | 路径段前缀 | /api 匹配 /api、/api/x,不匹配 /apix |
ImplementationSpecific | 由 Ingress 实现决定 | 不要用,不同实现行为不同 |
跨 Service 路由的常见需求:
/api/order/** → order-api:80
/api/user/** → user-api:80
配置:
- path: /api/order
pathType: Prefix
backend: { service: { name: order-api, port: { number: 80 }}}
⚠️ 注意路径重写:如果后端服务期望的是 /order/** 而不是 /api/order/**,需要配置重写。
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
rules:
- http:
paths:
- path: /api/order(/|$)(.*)
pathType: ImplementationSpecific
backend:
service:
name: order-api
port: { number: 80 }
资源 requests 与 limits
这是 K8s 里最容易配错的地方。
CPU:可压缩资源
resources:
requests:
cpu: 500m # 调度依据,保证至少 0.5 核
limits:
cpu: 1000m # 上限,超过会被限流(CPU throttle)
CPU 超过 limit 的表现:
容器被 CFS 限流 → 运行变慢(不是被杀)
kubelet 每 100ms 检查一次,超了就 throttle
监控指标:container_cpu_cfs_throttled_seconds_total
内存:不可压缩资源
resources:
requests:
memory: 512Mi
limits:
memory: 1Gi
内存超过 limit 的表现:直接 OOMKilled。
$ kubectl describe pod
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
requests 与 limits 的配置策略
┌──────────────────────────────────────────────┐
│ 场景 │ requests │ limits │
├──────────────────────────────────────────────┤
│ 稳定在线服务 │ 实际的 70% │ requests × 1.5│
│ 突发流量服务 │ 实际的 40% │ requests × 3 │
│ 批处理/离线任务 │ 单任务需要 │ 单任务需要 │
│ 有状态数据库 │ 实际需求 │ 实际需求 │
└──────────────────────────────────────────────┘
在线服务的推荐配比:
CPU: requests = 峰值的 50%,limits = 峰值的 100%
原因:CPU 密集时可以压到 limit,只是变慢不会死
内存: requests = 稳态的 80%,limits = 峰值的 100%
原因:内存超限会 OOMKilled,必须留足余量
为什么 requests 要小于 limits:
requests 低 → 调度更密集(一个节点能放更多 Pod)
requests = limits → 资源利用效率低
requests 是「保证」,limits 是「上限」
JVM 与容器的关系
// ❌ 危险:JVM 默认堆 = 1/4 物理内存
// 在容器里如果不限制,它会看到宿主机的全部内存
// 然后申请 128GB 堆,Pod 实际只有 2GB
// ✅ 容器感知
container {
// JDK 10+ 默认开启
java {
runtimeOptions = ["-XX:+UseContainerSupport"]
}
}
# ✅ 推荐配置
JAVA_OPTS="
-XX:MaxRAMPercentage=75 # 堆占容器内存的 75%
-XX:MaxDirectMemorySize=256m # 限制堆外内存
-XX:MaxMetaspaceSize=128m # 限制元空间
-XX:+ExitOnOutOfMemoryError # OOM 时直接退出,让 K8s 重启
"
K8s 的三个 QoS 等级:
| QoS | 条件 | 优先级 |
|---|---|---|
Guaranteed | requests == limits(所有容器) | 最高 |
Burstable | 部分设置了 requests/limits | 中 |
BestEffort | 都没设置 | 最低,最先被驱逐 |
生产核心服务建议用 Guaranteed:
resources:
requests:
cpu: 1000m
memory: 1Gi
limits:
cpu: 1000m # 与 requests 相同
memory: 1Gi
常用命令
# 查看资源使用
kubectl top pod
kubectl top node
kubectl top pod --containers
# 查看事件(排查 Pending 的第一步)
kubectl describe pod <name>
kubectl get events --sort-by=.lastTimestamp | tail -20
# 进入 Pod 调试
kubectl exec -it <pod> -- sh
kubectl exec -it <pod> -- curl localhost:8080/health
# 端口转发(本地调试)
kubectl port-forward pod/order-api-xxx 8080:8080
# 查看资源限额
kubectl describe node | grep -A5 "Allocated resources"
# 找出可以调度的节点
kubectl describe pod <pod> | grep -A10 Events
# 临时容器(调试用,1.25+)
kubectl debug -it <pod> --image=busybox --target=order-api
# 清理
kubectl delete pod --field-selector=status.phase=Failed
kubectl delete event --all
常见问题排查
Pod 一直 CrashLoopBackOff
$ kubectl describe pod order-api-xxx
Last State: Terminated
Exit Code: 1
$ kubectl logs order-api-xxx --previous # 关键:看上一个容器的日志
排查清单:
① 启动命令是否正确
② 配置(ConfigMap/Secret)是否挂载成功
③ 依赖服务是否可达(数据库、Redis)
④ 资源是否不足(被 OOMKilled)
⑤ 健康检查配置是否过严
健康检查的常见错误
# ❌ 过于严格:依赖外部服务,外部挂了 Pod 就重启(雪崩)
livenessProbe:
httpGet:
path: /health
port: 8080
# 错误示例:/health 里查了数据库
# ✅ liveness 只检查进程自身存活
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
# ✅ readiness 检查能否接收流量
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
periodSeconds: 5
failureThreshold: 2
# ✅ startupProbe 给慢启动应用更多时间
startupProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
failureThreshold: 30
periodSeconds: 10
三种探针的职责:
liveness → 失败则重启容器(回答「还活着吗」)
readiness → 失败则摘除流量(回答「能干活吗」)
startup → 启动期间保护(回答「启动完了吗」)
最经典的错误:把数据库连接放进 liveness。数据库抖动 → 所有 Pod 同时重启 → 数据库更抖 → 雪崩。
上线检查清单
【资源】
□ 每个容器都设置了 requests 和 limits
□ 内存 limits 足够(考虑 JVM 堆外内存)
□ CPU requests < CPU limits(提高调度密度)
□ 用了 Guaranteed QoS(核心服务)
【健康检查】
□ liveness 不依赖外部服务
□ readiness 检查了关键依赖
□ 慢启动应用配了 startupProbe
□ initialDelaySeconds 足够启动时间
【滚动更新】
□ 用了 RollingUpdate
□ maxSurge 和 maxUnavailable 配置合理
□ 有回滚方案(kubectl rollout undo)
【网络】
□ Service selector 与 Pod labels 匹配
□ 生产用 Ingress,不用 NodePort
□ 配置了 NetworkPolicy(可选)
【配置】
□ 配置用 ConfigMap,不硬编码
□ 敏感信息用 Secret + 加密
□ 有资源限制的 Pod QoS 是 Guaranteed 或 Burstable
最后
K8s 的核心概念其实只有几个:
Pod = 最小调度单元(不可变)
Deployment = 管理 Pod 的副本和更新
Service = 稳定的访问入口(解耦 Pod IP)
Ingress = 外部流量入口(域名 + TLS)
最重要的两条实践:
- 资源 requests 必须设置,否则调度器无法决策,也是 OOM 的根源
- liveness 探针不能依赖外部服务,否则会引发雪崩
其他配置都是这两个的延伸。