Skip to main content

网络与 Service

Pod IP 会变、副本会加减。Service 在一组 Pod 前面提供稳定的访问入口(虚 IP + DNS)。对外暴露站点时,常见路径是 Service + Ingress(或云负载均衡)。

标签与选择器

Service 通过 label selector 找到后端 Pod(与 Deployment 的 selector 同一套标签语言)。

# Pod / Deployment template 上
labels:
app: web
tier: frontend

# Service
selector:
app: web

改标签导致选不中 → Service 背后 Endpoints 为空 → 访问超时。排障先看:

kubectl get svc,endpoints -l app=web
kubectl get pods -l app=web --show-labels

Service 类型

类型集群内集群外典型用途
ClusterIP(默认)✓ 虚 IP✗(默认)服务间调用
NodePort经节点 IP:端口演示、简单暴露
LoadBalancer云厂商 LB生产对外(看云)
ExternalNameDNS 别名指到外部域名

最小 ClusterIP:

apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
ports:
- port: 80 # Service 端口
targetPort: 8080 # 容器端口

同 Namespace 内其他 Pod 可用 DNS:webweb.<namespace>.svc.cluster.local

集群 DNS 直觉

谁访谁怎么写
同 ns 内http://web:80
跨 nshttp://web.other-ns.svc.cluster.local
容器里的 localhost只是该容器自己,不是 Service

这和 Compose 里「用服务名而非 localhost」是同一心智模型。

Ingress 直觉

Ingress 在 HTTP(S) 层按域名 / 路径把流量转到后端 Service(需要集群里有 Ingress Controller,如 nginx / traefik)。

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
spec:
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
对象作用
ServiceL4(大体)稳定转发到 Pod
IngressL7 HTTP主机名、路径、TLS 终结(视实现)

没有 Ingress Controller 时,光有 Ingress 对象不会生效——以团队集群文档为准。

kube-proxy(面试级一句话)

节点上的 kube-proxy(或替代数据面)根据 Service/Endpoints 编程转发规则(iptables / IPVS / 等)。你排障时更常看 Endpoints 是否空,而不是手改 kube-proxy。

要点

  1. Service 用标签选中 Pod;标签不对 = 没后端
  2. 默认 ClusterIP 只给集群内;对外靠 NodePort / LB / Ingress
  3. DNS 用服务名;容器 localhost ≠ 别的服务
  4. Ingress 依赖 Controller;先确认集群装了哪一种

面试速记

  1. Service 三种常用类型? ClusterIP、NodePort、LoadBalancer。
  2. 为什么需要 Service? Pod IP 不稳定、副本多变;Service 提供稳定入口与负载均衡。
  3. Ingress 和 Service 区别? Service 转发到 Pod;Ingress 做 HTTP 路由到 Service。
  4. Endpoints 为空说明什么? selector 没命中就绪 Pod(标签、Namespace、readiness)。
  5. kube-proxy 作用? 在节点上实现 Service 流量转发规则。