入门教程 - K8s 核心对象与调度原理

知识库
知识库文档
/tech-stacks/kubernetes/tutorial/入门教程 - K8s 核心对象与调度原理.md

文档

Kubernetes 入门教程:核心对象与调度原理

1. 为什么需要 K8s?

Docker 解决单机容器问题,但生产环境有几十上百台机器:

  • 容器放哪台机器?(调度)
  • 机器挂了容器怎么办?(自愈)
  • 流量大了怎么扩容?(自动伸缩)
  • 服务之间怎么发现?(网络)
  • 配置怎么管理?(配置中心)

Kubernetes 统一解决上述问题,将数据中心视为一台计算机。

2. 核心对象图谱

Cluster
├── Namespace (逻辑隔离)
│   ├── Pod (最小调度单元,1+ 容器共享网络)
│   │   ├── Container
│   │   └── Volume
│   ├── Deployment (管理 Pod 副本,滚动更新)
│   ├── ReplicaSet (维护固定数量 Pod)
│   ├── Service (Pod 网络抽象,稳定 IP/DNS)
│   ├── ConfigMap / Secret (配置解耦)
│   └── Ingress (七层路由,域名 → Service)
├── PersistentVolume / PersistentVolumeClaim
└── Node (物理/虚拟机)

3. Pod 详解

Pod 是 K8s 最小调度单元,一个 Pod 内所有容器共享网络 namespace 和 IPC

spec:
  containers:
  - name: app
    image: myapp:latest
    ports: [containerPort: 5000]
  - name: sidecar  # 日志收集 sidecar
    image: fluentd:latest
    volumeMounts:
    - name: logs
      mountPath: /var/log/app

Pod 生命周期

Pending → Running → Succeeded (正常退出)
                   → Failed (异常退出)
     → Unknown

探针类型

探针 作用 失败后果
livenessProbe 容器是否存活 重启容器
readinessProbe 是否可接受流量 从 Service Endpoint 移除
startupProbe 启动是否完成 阻塞其他探针

4. Service 类型

类型 访问范围 使用场景
ClusterIP 集群内部 后端服务间通信
NodePort 节点 IP + 端口 开发调试
LoadBalancer 外部 LB 生产对外暴露
ExternalName DNS CNAME 外部服务映射

5. 调度机制

K8s 调度器通过 Filtering(过滤)→ Scoring(打分) 选择最优 Node:

# 节点亲和性
affinity:
  nodeAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
      nodeSelectorTerms:
      - matchExpressions:
        - key: disktype
          operator: In
          values: [ssd]

# Pod 反亲和性(分散部署)
podAntiAffinity:
  preferredDuringSchedulingIgnoredDuringExecution:
  - weight: 100
    podAffinityTerm:
      topologyKey: kubernetes.io/hostname

6. 思考题

  1. Deployment 和 StatefulSet 的核心区别?什么场景用 StatefulSet?
  2. Service 如何实现 Pod 发现?kube-proxy 的 iptables 和 IPVS 模式有何不同?
  3. 为什么建议一个 Pod 只跑一个容器?Sidecar 模式的例外场景有哪些?

信息

路径
/tech-stacks/kubernetes/tutorial/入门教程 - K8s 核心对象与调度原理.md
更新时间
2026/5/31