Skip to content

CNI 插件体系

CNI 概述

CNI(Container Network Interface)是 Kubernetes 网络插件的标准接口。kubelet 在创建 Pod 时调用 CNI 插件配置网络,删除 Pod 时调用 CNI 插件清理网络。

kubelet
  │ 调用 CNI 二进制
  ├── /opt/cni/bin/calico
  ├── /opt/cni/bin/cilium-cni
  └── /opt/cni/bin/flannel
  │ 读取配置
  └── /etc/cni/net.d/10-calico.conflist

Flannel(入门首选)

最简单的 CNI 插件,适合学习和小规模场景:

yaml
# Flannel 使用 VXLAN 封装跨节点流量
# 每个节点分配 /24 子网
# 通过 flannel.1 虚拟接口封装 UDP 包

# 安装
kubectl apply -f https://github.com/flannel-io/flannel/releases/latest/download/kube-flannel.yml

Calico(生产主流)

支持 BGP 路由和丰富的网络策略:

yaml
# 安装 Calico
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.27.0/manifests/tigera-operator.yaml

# 配置
apiVersion: operator.tigera.io/v1
kind: Installation
metadata:
  name: default
spec:
  calicoNetwork:
    ipPools:
    - blockSize: 26
      cidr: 10.244.0.0/16
      encapsulation: VXLANCrossSubnet  # 同子网 BGP,跨子网 VXLAN
      natOutgoing: Enabled

Calico 网络策略

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    - namespaceSelector:
        matchLabels:
          name: production
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: database
    ports:
    - protocol: TCP
      port: 5432
  # 允许 DNS
  - to:
    - namespaceSelector: {}
    ports:
    - protocol: UDP
      port: 53

Cilium(高性能 eBPF)

基于 eBPF 实现,绕过 iptables,性能极高,支持 L7 策略:

bash
# 安装 Cilium
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium --version 1.15.0 \
  --namespace kube-system \
  --set kubeProxyReplacement=true \  # 替换 kube-proxy
  --set k8sServiceHost=<API_SERVER_IP> \
  --set k8sServicePort=6443
yaml
# Cilium L7 网络策略(HTTP 级别)
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: l7-policy
spec:
  endpointSelector:
    matchLabels:
      app: backend
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: frontend
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
      rules:
        http:
        - method: GET
          path: /api/.*
        - method: POST
          path: /api/users

常用排查命令

bash
# 查看 CNI 配置
cat /etc/cni/net.d/10-calico.conflist

# Calico 节点状态
kubectl exec -n calico-system calico-node-xxx -- calicoctl node status

# Cilium 状态
kubectl exec -n kube-system cilium-xxx -- cilium status
kubectl exec -n kube-system cilium-xxx -- cilium endpoint list

# 查看 Pod 网络接口
kubectl exec my-pod -- ip addr
kubectl exec my-pod -- ip route

本站内容由 褚成志 整理编写,仅供学习参考