在 Kubernetes 中,Service
、Pod
和 Endpoints
之间的关系如下:
1. Pod 是运行应用的最小单元
- 每个
Pod
都有一个唯一的 Pod IP(仅在 Pod 存活期间有效)。 Pod
内部的容器可以通过localhost
访问彼此,但外部访问时需要Service
。
2. Service 作用:统一访问入口
Service
提供了一个 稳定的访问 IP(ClusterIP),Pod 可能会重启,但Service
的ClusterIP
不变。- 通过 标签选择器(Selector) 绑定后端的 Pod(多个)。
Service
监听端口(Port)并将请求转发到后端Pod
。
3. Endpoints 记录 Pod 信息
Endpoints
资源存储了Service
实际对应的 Pod IP 地址,即Service
选择的 Pod 列表。- 当 Pod 变化时,Endpoints 也会自动更新,但
Service
本身的ClusterIP
不会变。
4. 关系总结
- Pod → 运行应用,每个 Pod 都有 Pod IP。
- Service → 提供 ClusterIP,代理请求到 Pod,执行负载均衡。
- Endpoints → 维护 Service 和 Pod 之间的映射,记录
Pod IP
。
示例:一个 Service 绑定多个 Pod
① Pod 部署
apiVersion: v1
kind: Pod
metadata:
name: pod-1
labels:
app: my-app
spec:
containers:
- name: app
image: my-app-image
apiVersion: v1
kind: Pod
metadata:
name: pod-2
labels:
app: my-app
spec:
containers:
- name: app
image: my-app-image
② Service
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
③ Endpoints
apiVersion: v1
kind: Endpoints
metadata:
name: my-service
subsets:
- addresses:
- ip: 10.244.0.2
- ip: 10.244.0.3
ports:
- port: 8080
5. 访问流程
-
**客户端访问
my-service
的ClusterIP
**。 -
Kubernetes
iptables/IPVS
规则:
- 查找
Endpoints
,获取后端Pod IP
(如10.244.0.2
)。 - 负载均衡后,将请求转发到选中的
Pod
。
- 查找
-
Pod 处理请求并返回数据。
6. 关键点
✅ Service
自身不存储 Pod 信息,而是 通过 Endpoints
维护 Pod 列表。
✅ Endpoints
负责 动态绑定 Pod,Pod 变更时,Endpoints
也会同步更新。
✅ Service 通过 iptables
或 IPVS
进行流量转发,让 Pod 内部的变更对外部透明。