Service 与网络
Pod 的 IP 是临时的(重启就变),Service 提供稳定的访问入口:负载均衡到一组 Pod,集群内用 Service 名访问。
Service 类型
- ClusterIP(默认):集群内部访问
- NodePort:每个节点开一个端口,外部可访问(测试用)
- LoadBalancer:云厂商负载均衡(生产)
- Ingress:7 层 HTTP 路由(域名 + 路径分流)
代码示例
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web # 匹配 Deployment 的标签
ports:
- port: 80 # Service 端口
targetPort: 80 # Pod 端口
type: ClusterIP
# 应用并查看
kubectl apply -f service.yaml
kubectl get svc
# 集群内访问
# curl http://web (Service 名即域名)
# NodePort 类型(外部访问)
# type: NodePort
# nodePort: 30080
# 访问 http://节点IP:30080