Kubernetes 提供了多种机制来管理服务发现、负载均衡和容器健康状态监控。本文将围绕以下几个方面展开:
Service 类型:ClusterIP、NodePort、Headless Service、LoadBalancer(MetallB)
Ingress 的实现原理
健康检查探针:Liveness、Readiness、Startup
一、Service 类型详解
1. ClusterIP
ClusterIP 是默认的 Service 类型,用于在集群内部暴露服务。外部无法直接访问。
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 8000 # Service 端口
targetPort: 80 # Pod 端口
type: ClusterIP # 可省略,默认即为 ClusterIP
注释:
port
: Service 对外提供的端口targetPort
: Pod 中容器监听的端口集群内可通过
nginx-service:8000
访问该服务
2. NodePort
NodePort 会在每个节点上开放一个静态端口,外部可通过 节点IP:端口
访问服务。
apiVersion: v1
kind: Service
metadata:
name: nginx-nodeport
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30080 # 可选,范围 30000-32767
type: NodePort
注释:
nodePort
: 若不指定,K8s 会自动分配一个端口外部访问方式:
http://<节点IP>:30080
3. Headless Service
Headless Service 不分配 ClusterIP,直接返回后端 Pod 的 IP 地址列表。适用于需要直接访问 Pod 的场景(如 StatefulSet)。
apiVersion: v1
kind: Service
metadata:
name: nginx-headless
spec:
clusterIP: None # 关键字段,表示 Headless
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
注释:
DNS 查询该 Service 会返回所有后端 Pod 的 IP
适用于自定义负载均衡或状态ful服务发现
4. LoadBalancer 与 MetallB
在云环境中,LoadBalancer 类型会自动分配外部负载均衡器。在裸金属环境中,可使用 MetallB 实现类似功能。
MetallB 支持两种模式:
Layer2 模式:通过 ARP/NDP 响应将虚拟 IP 映射到某个节点
BGP 模式:通过 BGP 协议向路由器宣告路由,实现负载均衡
apiVersion: v1
kind: Service
metadata:
name: nginx-lb
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
注释:
在支持 LoadBalancer 的云平台中,会自动分配外部 IP
在裸金属环境中需安装并配置 MetallB
二、Ingress 原理与功能
Ingress 是管理外部访问集群服务的 API 对象,通常用于 HTTP/HTTPS 路由。
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: example-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: api-service
port:
number: 80
注释:
host
: 域名规则path
: 路径匹配规则backend
: 转发到的 Service
Ingress 需配合 Ingress Controller(如 nginx-ingress、traefik)使用。
三、健康检查探针
Kubernetes 提供三种探针来监控容器健康状态:
1. Liveness Probe(存活探针)
用于检测容器是否存活,失败则会重启容器。
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 10 # 容器启动后等待10秒开始检测
periodSeconds: 5 # 每5秒检测一次
适用场景:检测死锁、应用无响应等。
2. Readiness Probe(就绪探针)
用于检测容器是否准备好接收流量,失败则从 Service 后端列表中移除。
readinessProbe:
exec:
command:
- cat
- /tmp/healthy
initialDelaySeconds: 5
periodSeconds: 5
适用场景:等待依赖服务启动、加载配置完成等。
3. Startup Probe(启动探针)
用于保护慢启动容器,避免在启动过程中被误杀。
startupProbe:
httpGet:
path: /startup
port: 8080
failureThreshold: 30 # 最多尝试30次
periodSeconds: 10 # 每10秒尝试一次
适用场景:启动时间较长的 Java 应用、数据库初始化等。
总结
Kubernetes 通过 Service 和 Ingress 提供了灵活的服务暴露方式,通过健康检查探针保障了应用的可靠性。合理使用这些机制,可以构建出高可用、易维护的云原生应用。
探针类型 | 作用 | 失败行为 |
---|---|---|
LivenessProbe | 检测容器是否存活 | 重启容器 |
ReadinessProbe | 检测容器是否就绪 | 从 Service 中移除 |
StartupProbe | 保护慢启动容器 | 不触发其他探针 |
建议根据应用特性合理配置探针,避免误判和频繁重启。