[toc]
概述
本文以试图使用各种实例,来记录network policy 的各种使用,提供模板为后续运维管理提供参考
sequenceDiagram
source pod->>egress: to target
egress-->>ingress: ...
ingress->> target pod: from source
ingress: 选中pod 允许向外访问的规则 egress: 向选中 pod 访问的规则 podSelector: 规则应用于哪些pod
禁止访问内网
某些pod,我们只需要他访问公网,而不允许访问k8s 内部各种网络,适用于有渗透风险的容器。
比如 golang playground 之类
graph LR
pod -- x --> 公网
pod --> 内部网络
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-internal
namespace: default
spec:
podSelector:
matchLabels:
role: public
policyTypes:
- Egress
ingress:
- from:
egress:
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 10.0.0.0/8 # 10.0.0.0 ~ 10.255.255.255
- 172.16.0.0/12 #172.16.0.0 ~ 172.31.255.255
- 192.168.0.0/16 # 192.168.0.0 ~ 192.168.255.255
禁止任何人访问
禁止任何人访问本namespace 下的所有pod
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
允许任何人访问
允许任何人访问本namespace 下的所有pod
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
ingress:
- {}
禁止访问任何网络
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Egress
允许访问任何网络
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
egress:
- {}
policyTypes:
- Egress
禁止任何入口流量以及出口流量
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress