02-网络体系
Kubernetes Service、Ingress、NetworkPolicy 全链路解析
学习目标
通过本模块学习,你将掌握:
- Kubernetes 网络四层架构
- Pod 间通信机制(CNI)
- Service 负载均衡原理
- Ingress 七层路由
- NetworkPolicy 网络隔离
- 网络故障排查技能
一、Kubernetes 网络四层架构
网络层级概览
┌─────────────────────────────────────────────────────────────┐
│ Kubernetes 网络体系 │
├─────────────────────────────────────────────────────────────┤
│ L2-L3: Pod 网络层 │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ CNI 插件 │ │ CNI 插件 │ │ CNI 插件 │ │
│ │ Flannel/ │ │ Calico/ │ │ Cilium/ │ │
│ │ Calico/ │ │ Cilium/ │ │ Weave │ │
│ │ Cilium │ │ Weave │ │ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ L4: Service 虚拟网络层 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ kube-proxy (iptables/IPVS) │ │
│ └─────────────────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ L5-L7: Ingress 层 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Nginx/HAProxy/Traefik/Istio Gateway │ │
│ └─────────────────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Out-bound: Egress 层 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ SNAT/Egress Gateway │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
网络设计原则
- 每个 Pod 都有独立 IP:Pod 间可以直接通信
- 无 NAT 通信:Pod 到 Pod 通信不经过 NAT
- 节点间通信:节点上的 Pod 可以与其他节点上的 Pod 通信
- 容器网络隔离:同一 Pod 内容器共享网络命名空间
二、Pod 网络通信(CNI 原理)
2.1 CNI 核心概念
CNI(Container Network Interface) 是容器网络的标准接口,负责为 Pod 配置网络。
CNI 工作流程
graph TD
A[Pod 创建] --> B[kubelet]
B --> C[调用 CNI 插件]
C --> D[创建网络接口]
D --> E[分配 IP 地址]
E --> F[配置路由规则]
F --> G[Pod 网络就绪]
CNI 插件职责
- 网络配置:创建虚拟网络接口
- IP 分配:为 Pod 分配唯一 IP
- 路由管理:配置跨节点路由
- 网络策略:实现网络隔离
2.2 主流 CNI 插件对比
插件 | 特点 | 适用场景 | 性能 | 功能丰富度 |
---|---|---|---|---|
Flannel | 简单易用 | 中小规模集群 | 中等 | 基础 |
Calico | 功能丰富 | 企业级部署 | 高 | 丰富 |
Cilium | 基于 eBPF | 高性能场景 | 很高 | 非常丰富 |
Weave | 自动发现 | 简单部署 | 中等 | 中等 |
2.3 Flannel 网络模型
VXLAN 模式
graph TD
A[Pod A<br/>10.244.1.2] --> B[veth pair]
B --> C[flannel.1<br/>VXLAN 接口]
C --> D[UDP 8472<br/>VXLAN 隧道]
D --> E[flannel.1<br/>目标节点]
E --> F[veth pair]
F --> G[Pod B<br/>10.244.2.3]
配置示例
# Flannel 配置
apiVersion: v1
kind: ConfigMap
metadata:
name: kube-flannel-cfg
namespace: kube-system
data:
cni-conf.json: |
{
"name": "cbr0",
"cniVersion": "0.3.1",
"plugins": [
{
"type": "flannel",
"delegate": {
"hairpinMode": true,
"isDefaultGateway": true
}
}
]
}
net-conf.json: |
{
"Network": "10.244.0.0/16",
"Backend": {
"Type": "vxlan"
}
}
2.4 Calico 网络模型
BGP 模式
graph TD
A[Pod A<br/>10.244.1.2] --> B[cali0]
B --> C[calico 路由表]
C --> D[BGP 协议]
D --> E[calico 路由表]
E --> F[cali0]
F --> G[Pod B<br/>10.244.2.3]
安装配置
# 安装 Calico
kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
# 查看 Calico 状态
kubectl get pods -n kube-system -l k8s-app=calico-node
# 查看 BGP 对等体
calicoctl node status
2.5 Cilium 网络模型
eBPF 模式
graph TD
A[Pod A] --> B[eBPF 程序]
B --> C[内核数据路径]
C --> D[直接转发]
D --> E[Pod B]
安装配置
# 安装 Cilium
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium --namespace kube-system
# 验证安装
cilium status
cilium connectivity test
三、Service 层(kube-proxy 原理)
3.1 Service 核心概念
Service 是 Kubernetes 中的服务抽象,为 Pod 提供稳定的网络访问入口。
Service 类型对比
类型 | 用途 | 访问方式 | 适用场景 |
---|---|---|---|
ClusterIP | 集群内访问 | 虚拟 IP | 内部服务通信 |
NodePort | 节点端口访问 | <NodeIP>:<Port> | 简单外部访问 |
LoadBalancer | 云负载均衡 | 云厂商分配 IP | 生产环境 |
ExternalName | 外部服务映射 | CNAME 解析 | 外部服务集成 |
3.2 kube-proxy 工作原理
iptables 模式
# 查看 iptables 规则
iptables -t nat -L KUBE-SERVICES
# 示例规则
-A KUBE-SERVICES -d 10.96.0.1/32 -p tcp -m tcp --dport 80 -j KUBE-SVC-XXXXX
-A KUBE-SVC-XXXXX -j KUBE-SEP-AAAAA # Pod 1
-A KUBE-SVC-XXXXX -j KUBE-SEP-BBBBB # Pod 2
IPVS 模式
# 查看 IPVS 规则
ipvsadm -ln
# 示例规则
TCP 10.96.0.1:80 rr
-> 10.244.1.2:80
-> 10.244.2.3:80
3.3 Service 配置示例
ClusterIP Service
apiVersion: v1
kind: Service
metadata:
name: web-service
spec:
type: ClusterIP
selector:
app: web
ports:
- port: 80
targetPort: 8080
protocol: TCP
NodePort Service
apiVersion: v1
kind: Service
metadata:
name: web-nodeport
spec:
type: NodePort
selector:
app: web
ports:
- port: 80
targetPort: 8080
nodePort: 30080
protocol: TCP
LoadBalancer Service
apiVersion: v1
kind: Service
metadata:
name: web-lb
spec:
type: LoadBalancer
selector:
app: web
ports:
- port: 80
targetPort: 8080
protocol: TCP
loadBalancerIP: 192.168.1.100 # 可选,指定 IP
3.4 Headless Service
apiVersion: v1
kind: Service
metadata:
name: web-headless
spec:
clusterIP: None # 关键:无 ClusterIP
selector:
app: web
ports:
- port: 80
targetPort: 8080
四、Ingress:七层流量入口
4.1 Ingress 核心概念
Ingress 是 Kubernetes 中的 HTTP/HTTPS 路由规则,提供七层负载均衡。
Ingress 组件
- Ingress Controller:实际的路由实现
- Ingress 资源:路由规则定义
- Backend Service:后端服务
4.2 主流 Ingress Controller
Controller | 特点 | 适用场景 |
---|---|---|
Nginx Ingress | 功能丰富,性能好 | 通用场景 |
HAProxy Ingress | 高性能,企业级 | 高并发场景 |
Traefik | 自动发现,云原生 | 微服务架构 |
Istio Gateway | 服务网格集成 | 复杂网络 |
4.3 Nginx Ingress 部署
安装 Ingress Controller
# 安装 Nginx Ingress Controller
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/cloud/deploy.yaml
# 验证安装
kubectl get pods -n ingress-nginx
kubectl get svc -n ingress-nginx
基本 Ingress 配置
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: web.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80
高级 Ingress 配置
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: advanced-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/rate-limit: "100"
nginx.ingress.kubernetes.io/rate-limit-window: "1m"
spec:
tls:
- hosts:
- web.example.com
secretName: web-tls
rules:
- host: web.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: api-service
port:
number: 80
- path: /static
pathType: Prefix
backend:
service:
name: static-service
port:
number: 80
4.4 Gateway API(下一代 Ingress)
Gateway API 优势
- 角色分离:GatewayClass、Gateway、HTTPRoute
- 多租户支持:不同团队管理不同资源
- 功能丰富:支持更多协议和功能
Gateway API 示例
apiVersion: gateway.networking.k8s.io/v1beta1
kind: GatewayClass
metadata:
name: nginx-gateway-class
spec:
controllerName: nginx.org/gateway-controller
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: Gateway
metadata:
name: web-gateway
spec:
gatewayClassName: nginx-gateway-class
listeners:
- name: http
port: 80
protocol: HTTP
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: HTTPRoute
metadata:
name: web-route
spec:
parentRefs:
- name: web-gateway
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: web-service
port: 80
五、NetworkPolicy 网络隔离
5.1 NetworkPolicy 核心概念
NetworkPolicy 是 Kubernetes 中的网络策略资源,用于控制 Pod 间的网络通信。
零信任网络模型
- 默认拒绝:所有流量默认被拒绝
- 显式允许:通过策略明确允许的流量
- 分层防护:按 namespace、label 分层管理
5.2 NetworkPolicy 工作原理
策略生效条件
- CNI 插件必须支持 NetworkPolicy
- 策略只对匹配的 Pod 生效
- 未匹配策略的 Pod 默认全通
- 定义策略但未显式允许则默认拒绝
5.3 NetworkPolicy 配置示例
基本策略
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-nginx
namespace: default
spec:
podSelector:
matchLabels:
app: nginx
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: app
ports:
- protocol: TCP
port: 80
双向策略
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-access
namespace: backend
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: frontend
ports:
- protocol: TCP
port: 3306
egress:
- to:
- ipBlock:
cidr: 10.0.0.0/24
except:
- 10.0.0.5/32
ports:
- protocol: TCP
port: 53
默认拒绝策略
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: default
spec:
podSelector: {} # 匹配所有 Pod
policyTypes:
- Ingress
- Egress
5.4 高级网络策略
按 Namespace 隔离
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: frontend-access
namespace: backend
spec:
podSelector:
matchLabels:
role: api
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: frontend
基于 IP 的策略
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-specific-ips
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Ingress
ingress:
- from:
- ipBlock:
cidr: 192.168.1.0/24
except:
- 192.168.1.100/32
️ 六、命令速记
网络诊断命令
# 查看 Pod 网络接口
kubectl exec <pod> -- ip addr
# 测试 Pod 间连通性
kubectl exec <pod1> -- ping <pod2-ip>
# 查看 Service 端点
kubectl get endpoints
kubectl get endpointslice
# 测试 Service 访问
kubectl exec <pod> -- curl <service-name>
# 查看 DNS 解析
kubectl exec <pod> -- nslookup <service-name>
CNI 相关命令
# 查看 Flannel 状态
kubectl get pods -n kube-system -l app=flannel
# 查看 Calico 状态
kubectl get pods -n kube-system -l k8s-app=calico-node
# 查看 Cilium 状态
cilium status
# 查看网络策略
kubectl get networkpolicy
kubectl describe networkpolicy <name>
Ingress 相关命令
# 查看 Ingress 状态
kubectl get ingress
kubectl describe ingress <name>
# 查看 Ingress Controller 日志
kubectl logs -n ingress-nginx <controller-pod>
# 测试 Ingress 访问
curl -H "Host: web.example.com" http://<ingress-ip>
七、面试核心问答
Q1: Pod 间是如何通信的?
答案要点:
- 每个 Pod 都有独立 IP
- 同节点 Pod 通过 veth pair 直连
- 跨节点 Pod 通过 CNI 插件(VXLAN/BGP/eBPF)
- 无需 NAT,直接路由
Q2: Service 是如何实现负载均衡的?
答案要点:
- kube-proxy 监听 Service 和 Endpoint
- 生成 iptables/IPVS 规则
- 将 Service IP 流量转发到 Pod IP
- 支持多种负载均衡算法
Q3: Ingress 与 Service 的区别?
答案要点:
- Service:四层(L4)负载均衡
- Ingress:七层(L7)HTTP/HTTPS 路由
- Ingress 依赖 Service 作为后端
- Ingress 支持域名、路径、SSL 等高级功能
Q4: NetworkPolicy 如何实现网络隔离?
答案要点:
- 默认拒绝所有流量
- 通过策略显式允许
- 支持 Pod、Namespace、IP 三层选择器
- 需要 CNI 插件支持
Q5: 如何排查网络问题?
答案要点:
- 检查 Pod 网络接口和路由
- 验证 Service 和 Endpoint 状态
- 测试 DNS 解析
- 查看 CNI 插件日志
- 使用网络诊断工具
八、故障排查
常见网络问题
1. Pod 间无法通信
# 检查 Pod 网络接口
kubectl exec <pod> -- ip addr
# 检查路由表
kubectl exec <pod> -- ip route
# 检查 CNI 插件状态
kubectl get pods -n kube-system -l app=flannel
# 测试连通性
kubectl exec <pod1> -- ping <pod2-ip>
2. Service 无法访问
# 检查 Service 状态
kubectl get svc
kubectl describe svc <name>
# 检查 Endpoint
kubectl get endpoints
kubectl get endpointslice
# 检查 kube-proxy
kubectl get pods -n kube-system -l k8s-app=kube-proxy
# 查看 iptables 规则
iptables -t nat -L KUBE-SERVICES
3. Ingress 无法访问
# 检查 Ingress 状态
kubectl get ingress
kubectl describe ingress <name>
# 检查 Ingress Controller
kubectl get pods -n ingress-nginx
# 查看 Controller 日志
kubectl logs -n ingress-nginx <controller-pod>
# 测试访问
curl -H "Host: <hostname>" http://<ingress-ip>
4. DNS 解析失败
# 检查 CoreDNS
kubectl get pods -n kube-system -l k8s-app=kube-dns
# 查看 CoreDNS 日志
kubectl logs -n kube-system <coredns-pod>
# 测试 DNS 解析
kubectl exec <pod> -- nslookup <service-name>
kubectl exec <pod> -- dig <service-name>
九、最佳实践
网络设计建议
CNI 选择
- 小规模:Flannel
- 企业级:Calico
- 高性能:Cilium
Service 设计
- 优先使用 ClusterIP
- 合理设置端口映射
- 使用 Headless Service 用于服务发现
Ingress 设计
- 使用 HTTPS
- 配置合理的重写规则
- 启用访问日志
网络策略
- 实施零信任模型
- 按业务分层管理
- 定期审查策略
性能优化
网络性能
- 使用高性能 CNI 插件
- 优化网络配置
- 监控网络指标
负载均衡
- 使用 IPVS 模式
- 配置合理的负载均衡算法
- 监控后端健康状态
十、总结
通过本模块学习,你已经掌握了:
- Kubernetes 网络四层架构
- Pod 间通信机制(CNI)
- Service 负载均衡原理
- Ingress 七层路由配置
- NetworkPolicy 网络隔离
- 网络故障排查技能
- 网络最佳实践
下一步建议:继续学习 03-存储管理,深入了解 Kubernetes 存储和状态管理机制。