网络策略(Network Policy),用于限制Pod出入流量,提供Pod级别和Namespace级别网络访问控制。
一些应用场景:
网络策略依赖cni插件,常用cni插件为flannel和calico,而flannel不支持网略策略,cni支持
podSelector:策略应用的pod
ingress:进流量,控制谁来访问我
egress:出流量,控制我能访问谁
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: default
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
project: default
- podSelector:
matchLabels:
run: client1
ports:
- protocol: TCP
port: 80
准备app=web
的一个pod
再准备两个pod:
kubectl run -it --rm client1 --image=busybox:1.28.4 sh
kubectl run -it --rm client2 --image=busybox:1.28.4 sh
[root@k8s-master network-policy]# kubectl get pod --show-labels
NAME READY STATUS RESTARTS AGE LABELS
client1 1/1 Running 0 12m run=client1
client2 1/1 Running 0 11m run=client2
web-5dcb957ccc-kb4vz 1/1 Running 0 22m app=web,pod-template-hash=5dcb957ccc
应用网略策略:
kubectl apply -f test-networkpolicy.yaml
[root@k8s-master network-policy]# kubectl get networkpolicy
NAME POD-SELECTOR AGE
test-network-policy app=web 41m
测试两个busybox的pod发现,run=client1的可以访问web pod,而client2不能
deny-from-other-namespace.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-from-other-namespaces
namespace: default
spec:
podSelector: {} # 不配置,默认是该命名空间下所有pod
policyTypes:
- Ingress
ingress:
- from:
- podSelector: {} #不配置,默认是不允许
准备两个pod
kubectl run -it --rm client1 --image=busybox:1.28.4 sh
kubectl run -it --rm client2 --image=busybox:1.28.4 sh -n kube-system
应用策略后,发现,client1可以访问client2,但client2却不能访问client1,client1也能访问同命名空间下的web pod。
“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill
标 题:Kubernetes安全框架(下)-网络策略