🔷 K8S Service与Pod关系详解

📚 核心概念

Service是Kubernetes中的抽象层,定义了一组逻辑上的Pod访问策略。它提供了一个稳定的网络入口,屏蔽了后端Pod的动态变化。

Pod是Kubernetes的最小部署单元,包含一个或多个容器。Pod有独立的IP地址,但这个IP会随着Pod的重启、迁移而变化。

Label是附加到K8S对象(如Pod)上的键值对,用于组织和选择对象子集。格式:key: value

Selector是Service连接Pod的桥梁!

Service通过selector字段定义标签选择器,用于匹配拥有对应标签的Pod。只有标签完全匹配的Pod才会被该Service代理。

🎨 交互式可视化

修改Selector规则,观察哪些Pod会被匹配到Service

📊 匹配结果

等待更新...

💡 Selector工作原理

1️⃣ 标签匹配流程

  • Step 1: 管理员创建Pod时,为Pod打上Label标签
  • Step 2: 创建Service时,在spec.selector中定义标签选择器
  • Step 3: K8S控制平面持续监控,将Selector与所有Pod的Label进行匹配
  • Step 4: 匹配成功的Pod被自动加入到Service的Endpoints列表
  • Step 5: Service将流量负载均衡到这些Pod

2️⃣ Selector类型

  • Equality-based (基于等值): environment = productionenvironment != qa
  • Set-based (基于集合): environment in (production, qa)environment notin (dev)
  • Service使用的Selector: 通常是简单的key: value映射(等值匹配)

3️⃣ YAML配置示例

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx      # 👈 这就是Selector!
    env: prod       # 必须同时匹配这两个标签
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx    # Pod的Label
      env: prod     # Pod的Label
  template:
    metadata:
      labels:
        app: nginx  # 👈 Pod模板中的Label定义
        env: prod
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 8080

🔑 关键规则总结

  • 多标签AND关系: Service的selector中所有键值对都必须匹配,Pod才会被选中
  • 动态更新: 当Pod的Label变化时,Service会自动更新Endpoints列表
  • 跨Namespace: Service默认只能选择同一Namespace内的Pod
  • 无Selector的Service: 可以创建没有selector的Service,手动配置Endpoints(用于访问外部服务)
  • 标签建议: 使用有意义的标签,如app, version, env, tier