Pod #

一、Pod概念 #

Pod是Kubernetes中最小的部署单元,包含一个或多个容器,这些容器共享存储、网络和运行配置。

1.1 Pod特点 #

text
Pod特性
    │
    ├── 共享网络
    │   ├── 同一IP地址
    │   ├── 共享网络命名空间
    │   └── localhost通信
    │
    ├── 共享存储
    │   ├── 共享Volume
    │   └── 数据共享
    │
    └── 共享配置
        ├── 环境变量
        ├── 配置文件
        └── 密钥

1.2 Pod结构 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.25
    ports:
    - containerPort: 80
    resources:
      requests:
        cpu: 100m
        memory: 128Mi
      limits:
        cpu: 200m
        memory: 256Mi
  nodeSelector:
    disktype: ssd

二、Pod生命周期 #

2.1 Pod阶段 #

text
Pod阶段 (Phase)
    │
    ├── Pending ─── 等待调度
    │
    ├── Running ─── 运行中
    │
    ├── Succeeded ─── 成功完成
    │
    ├── Failed ─── 运行失败
    │
    └── Unknown ─── 状态未知

2.2 Pod状态 #

bash
# 查看Pod状态
kubectl get pod <pod-name> -o jsonpath='{.status.phase}'

# 查看Pod条件
kubectl get pod <pod-name> -o jsonpath='{.status.conditions[*].type}'
条件类型 说明
PodScheduled Pod已调度到节点
Initialized 初始化容器完成
ContainersReady 所有容器就绪
Ready Pod就绪,可接收流量

2.3 容器状态 #

text
容器状态
    │
    ├── Waiting ─── 等待状态
    │   ├── ContainerCreating
    │   ├── CrashLoopBackOff
    │   └── ImagePullBackOff
    │
    ├── Running ─── 运行状态
    │
    ├── Terminated ─── 终止状态
    │
    └── Unknown ─── 未知状态

2.4 生命周期钩子 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: nginx
    image: nginx
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo 'Container started' > /var/log/message"]
      preStop:
        exec:
          command: ["/bin/sh", "-c", "nginx -s quit"]

三、多容器模式 #

3.1 Sidecar模式 #

Sidecar容器辅助主容器工作。

yaml
apiVersion: v1
kind: Pod
metadata:
  name: sidecar-demo
spec:
  containers:
  - name: app
    image: nginx
    volumeMounts:
    - name: logs
      mountPath: /var/log/nginx
  - name: log-collector
    image: busybox
    command: ["sh", "-c", "tail -f /logs/access.log"]
    volumeMounts:
    - name: logs
      mountPath: /logs
  volumes:
  - name: logs
    emptyDir: {}

3.2 Ambassador模式 #

Ambassador容器代理主容器的网络请求。

yaml
apiVersion: v1
kind: Pod
metadata:
  name: ambassador-demo
spec:
  containers:
  - name: app
    image: nginx
    env:
    - name: DB_HOST
      value: "127.0.0.1"
  - name: ambassador
    image: haproxy:2.4
    ports:
    - containerPort: 3306

3.3 Adapter模式 #

Adapter容器转换主容器的输出格式。

yaml
apiVersion: v1
kind: Pod
metadata:
  name: adapter-demo
spec:
  containers:
  - name: app
    image: nginx
    volumeMounts:
    - name: logs
      mountPath: /var/log/nginx
  - name: adapter
    image: busybox
    command: ["sh", "-c", "while true; do cat /logs/access.log | grep -v 'health' > /logs/filtered.log; sleep 5; done"]
    volumeMounts:
    - name: logs
      mountPath: /logs
  volumes:
  - name: logs
    emptyDir: {}

四、初始化容器 #

初始化容器在主容器启动前运行,用于初始化工作。

4.1 基本用法 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  initContainers:
  - name: init-myservice
    image: busybox
    command: ['sh', '-c', 'echo "Initializing..." && sleep 5']
  containers:
  - name: nginx
    image: nginx

4.2 等待依赖服务 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: myapp
spec:
  initContainers:
  - name: wait-for-db
    image: busybox
    command: ['sh', '-c', 'until nc -z mysql-service 3306; do echo waiting for mysql; sleep 2; done']
  containers:
  - name: myapp
    image: myapp:latest

4.3 初始化配置 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: config-init
spec:
  initContainers:
  - name: setup-config
    image: busybox
    command: ['sh', '-c', 'echo "config content" > /config/app.conf']
    volumeMounts:
    - name: config
      mountPath: /config
  containers:
  - name: app
    image: nginx
    volumeMounts:
    - name: config
      mountPath: /etc/app
  volumes:
  - name: config
    emptyDir: {}

五、资源管理 #

5.1 资源请求与限制 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: resource-demo
spec:
  containers:
  - name: nginx
    image: nginx
    resources:
      requests:
        cpu: 100m
        memory: 128Mi
      limits:
        cpu: 200m
        memory: 256Mi

5.2 资源单位 #

资源 单位 说明
CPU m (millicore) 1000m = 1 CPU
CPU 整数 1 = 1 CPU
内存 Ki, Mi, Gi 二进制单位
内存 K, M, G 十进制单位

5.3 QoS等级 #

text
QoS等级
    │
    ├── Guaranteed
    │   ├── requests = limits
    │   └── 最高优先级
    │
    ├── Burstable
    │   ├── requests < limits
    │   └── 中等优先级
    │
    └── BestEffort
        ├── 无requests/limits
        └── 最低优先级

六、健康检查 #

6.1 存活探针 #

存活探针检测容器是否运行,失败则重启容器。

yaml
apiVersion: v1
kind: Pod
metadata:
  name: liveness-demo
spec:
  containers:
  - name: nginx
    image: nginx
    livenessProbe:
      httpGet:
        path: /health
        port: 80
      initialDelaySeconds: 10
      periodSeconds: 10
      timeoutSeconds: 5
      failureThreshold: 3

6.2 就绪探针 #

就绪探针检测容器是否准备好接收流量。

yaml
apiVersion: v1
kind: Pod
metadata:
  name: readiness-demo
spec:
  containers:
  - name: nginx
    image: nginx
    readinessProbe:
      httpGet:
        path: /ready
        port: 80
      initialDelaySeconds: 5
      periodSeconds: 5
      failureThreshold: 3

6.3 启动探针 #

启动探针检测容器是否启动完成。

yaml
apiVersion: v1
kind: Pod
metadata:
  name: startup-demo
spec:
  containers:
  - name: nginx
    image: nginx
    startupProbe:
      httpGet:
        path: /health
        port: 80
      initialDelaySeconds: 0
      periodSeconds: 10
      failureThreshold: 30

6.4 探针类型 #

yaml
# HTTP探针
livenessProbe:
  httpGet:
    path: /health
    port: 80
    httpHeaders:
    - name: Custom-Header
      value: value

# TCP探针
livenessProbe:
  tcpSocket:
    port: 80

# 命令探针
livenessProbe:
  exec:
    command:
    - cat
    - /tmp/health

七、调度策略 #

7.1 节点选择器 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
  nodeSelector:
    disktype: ssd

7.2 节点亲和性 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/arch
            operator: In
            values:
            - amd64
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 1
        preference:
          matchExpressions:
          - key: disktype
            operator: In
            values:
            - ssd
  containers:
  - name: nginx
    image: nginx

7.3 Pod亲和性 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  affinity:
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchLabels:
            app: cache
        topologyKey: kubernetes.io/hostname
    podAntiAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchLabels:
              app: nginx
          topologyKey: kubernetes.io/hostname
  containers:
  - name: nginx
    image: nginx

7.4 污点和容忍 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  tolerations:
  - key: "dedicated"
    operator: "Equal"
    value: "gpu"
    effect: "NoSchedule"
  containers:
  - name: nginx
    image: nginx

八、临时容器 #

临时容器用于调试运行中的Pod。

bash
# 创建临时容器
kubectl debug -it <pod-name> --image=busybox

# 复制Pod调试
kubectl debug <pod-name> -it --copy-to=debug-pod --image=busybox

# 节点调试
kubectl debug node/<node-name> -it --image=busybox

九、Pod安全 #

9.1 安全上下文 #

yaml
apiVersion: v1
kind: Pod
metadata:
  name: security-demo
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
  containers:
  - name: nginx
    image: nginx
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop: ["ALL"]

9.2 安全配置选项 #

选项 说明
runAsUser 以指定用户运行
runAsGroup 以指定组运行
fsGroup 文件系统组
readOnlyRootFilesystem 只读根文件系统
allowPrivilegeEscalation 禁止权限提升
capabilities Linux能力控制

十、Pod故障排查 #

10.1 常见状态 #

状态 原因 解决方案
Pending 资源不足 增加资源或节点
CrashLoopBackOff 容器崩溃 检查日志和配置
ImagePullBackOff 镜像拉取失败 检查镜像名称和权限
CreateContainerConfigError 配置错误 检查ConfigMap/Secret
Evicted 资源驱逐 检查节点资源

10.2 排查命令 #

bash
# 查看Pod详情
kubectl describe pod <pod-name>

# 查看Pod日志
kubectl logs <pod-name>

# 查看之前容器日志
kubectl logs <pod-name> --previous

# 进入容器
kubectl exec -it <pod-name> -- /bin/bash

# 查看事件
kubectl get events --field-selector involvedObject.name=<pod-name>

十一、总结 #

11.1 Pod核心要点 #

要点 说明
定义 最小部署单元
特点 共享网络、存储
生命周期 Pending → Running → Succeeded/Failed
健康检查 Liveness、Readiness、Startup
资源管理 Requests、Limits、QoS
调度策略 亲和性、污点容忍

11.2 下一步 #

掌握了Pod的使用后,让我们学习 命名空间,了解如何进行资源隔离和多租户管理。

最后更新:2026-03-28