Calico 网络策略
Calico 概述
Calico 是生产环境最广泛使用的 CNI 插件,支持 BGP 路由、丰富的网络策略、多种封装模式。
网络模式
BGP 模式(推荐,无封装开销):
节点间通过 BGP 协议交换路由,直接路由 Pod 流量
VXLAN 模式(跨子网场景):
封装 UDP 包,适合节点不在同一二层网络
IPinIP 模式:
轻量封装,适合同一二层网络的跨子网场景安装
bash
# 使用 Operator 安装
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.27.0/manifests/tigera-operator.yaml
cat <<EOF | kubectl apply -f -
apiVersion: operator.tigera.io/v1
kind: Installation
metadata:
name: default
spec:
calicoNetwork:
ipPools:
- blockSize: 26
cidr: 10.244.0.0/16
encapsulation: VXLANCrossSubnet
natOutgoing: Enabled
nodeSelector: all()
EOF网络策略
默认拒绝所有流量
yaml
# 命名空间级别默认拒绝
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {} # 选中所有 Pod
policyTypes:
- Ingress
- Egress精细化策略
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-policy
namespace: production
spec:
podSelector:
matchLabels:
tier: backend
policyTypes:
- Ingress
- Egress
ingress:
# 只允许来自 frontend 的流量
- from:
- podSelector:
matchLabels:
tier: frontend
ports:
- protocol: TCP
port: 8080
egress:
# 允许访问数据库
- to:
- podSelector:
matchLabels:
tier: database
ports:
- protocol: TCP
port: 5432
# 允许 DNS
- to:
- namespaceSelector: {}
ports:
- protocol: UDP
port: 53
# 允许访问外部 API
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
ports:
- protocol: TCP
port: 443Calico 全局网络策略(跨命名空间)
yaml
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: deny-nodeport
spec:
selector: all()
ingress:
- action: Deny
protocol: TCP
destination:
ports: [30000:32767]
order: 100常用命令
bash
# 查看 Calico 节点状态
kubectl exec -n calico-system calico-node-xxx -- calicoctl node status
# 查看 BGP 对等体
kubectl exec -n calico-system calico-node-xxx -- calicoctl get bgppeers
# 查看 IP 池
kubectl exec -n calico-system calico-node-xxx -- calicoctl get ippools -o wide
# 查看网络策略
calicoctl get networkpolicy -n production
# 查看 Felix 日志(网络策略执行引擎)
kubectl logs -n calico-system calico-node-xxx -c calico-node | grep felix