Kubernetes Pod 详解
Pod 的概念
Pod 是 Kubernetes 中最小的可部署计算单元,代表集群中运行的一个进程实例。一个 Pod 封装一个或多个容器(通常为一个主容器和若干辅助容器),共享存储、网络和运行配置。
为什么需要 Pod
- 共享网络空间:Pod 内的容器共享 IP 地址和端口空间,可以通过 localhost 通信
- 共享存储卷:Pod 内的容器可以挂载相同的 Volume 来共享数据
- 生命周期绑定:Pod 内的容器一同创建、一同销毁
Pod 的定义
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
tier: frontend
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
livenessProbe:
httpGet:
path: /healthz
port: 80
initialDelaySeconds: 5
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 80
initialDelaySeconds: 3
periodSeconds: 5
Pod 生命周期
状态流转
Pending → Running → Succeeded
↓ ↓
Failed Unknown
| 状态 | 说明 |
|---|---|
| Pending | Pod 已被接受但尚未调度或镜像未拉取完成 |
| Running | Pod 已被调度到节点,所有容器已创建且至少一个在运行 |
| Succeeded | Pod 中所有容器正常退出(适用于 Job) |
| Failed | Pod 中至少一个容器以非零状态退出 |
| Unknown | 无法获取 Pod 状态,通常是因为通信失败 |
Init 容器
Init 容器在主容器启动前运行,用于执行初始化任务:
spec:
initContainers:
- name: init-db
image: busybox:1.36
command: ['sh', '-c', 'until nc -z db-service 5432; do sleep 2; done;']
containers:
- name: app
image: myapp:latest
探针 (Probe)
三种探针
| 探针类型 | 用途 | 失败后果 |
|---|---|---|
| livenessProbe | 检测容器是否存活 | 重启容器 |
| readinessProbe | 检测容器是否就绪 | 从 Service Endpoint 移除 |
| startupProbe | 检测容器是否已启动 | 延迟 liveness 检查 |
检测方式
# HTTP 请求
livenessProbe:
httpGet:
path: /health
port: 8080
httpHeaders:
- name: X-Custom-Header
value: healthcheck
# TCP 端口
readinessProbe:
tcpSocket:
port: 3306
initialDelaySeconds: 10
# 命令执行
livenessProbe:
exec:
command:
- cat
- /tmp/healthy
资源管理
Requests 和 Limits
resources:
requests:
cpu: 250m # 保证 0.25 核
memory: 256Mi # 保证 256 MiB
limits:
cpu: 1 # 最高使用 1 核
memory: 512Mi # 最高使用 512 MiB
- requests:调度依据,保证 Pod 能获得的最小资源
- limits:资源上限约束,超过限制会被 OOM Kill 或 CPU 节流
调度策略
节点选择
spec:
nodeSelector:
disktype: ssd
tolerations:
- key: "gpu"
operator: "Exists"
effect: "NoSchedule"
亲和性规则
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- web
topologyKey: kubernetes.io/hostname
总结
Pod 是 Kubernetes 世界最基本的构建块,理解 Pod 的设计原理、生命周期和资源配置,是掌握 Kubernetes 的基础。在实际使用中,通常不直接创建 Pod,而是通过 Deployment、StatefulSet 等控制器来管理 Pod。