Network policy:设置pod进出网络的策略,k8s本身并不支持,主要靠以下网络插件来支持。
- calico
- Romana
- Weave
network policy 策略模型
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: default
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- ipBlock:
cidr: 172.17.0.0/16
except:
- 172.17.1.0/24
- namespaceSelector:
matchLabels:
project: myproject
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
egress:
- to:
- ipBlock:
cidr: 10.0.0.0/24
ports:
- protocol: TCP
port: 5978
上述规则意思如下:
入站
- default namespace下含有label role=db的pod,不满足ingress和exgress的网络访问(出去,进入)都会被拒绝
- default namespace下含有label role=db的pod,172.17.0.0/16(除去172.17.1.0/24)的网络可以访问,其他的都被拒绝
- default namespace下含有label role=db的pod,在label为project=myproject的namespace下都能访问到
+default namespace下含有label role=db的pod,在default namespace下只有label为role=frontend的pod能访问 - ports 为只能访问的port,不写所有ports都能访问
出站
- default namespace下含label为role=db的pod,只能访问10.0.0.0/24 ,对应port的目标
典型规则的配置
1.同namespace的pod,入站规则为全部禁止
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
2.同namespace的pod,入站规则为全部开放:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
ingress:
- {}
3.同namespace的pod,出站规则为全部禁止
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Egress
4.同namespace的pod,出站规则为全部开放
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
egress:
- {}
policyTypes:
- Egress