Network policy:設置pod進出網(wǎng)絡的策略锉罐,k8s本身并不支持而姐,主要靠以下網(wǎng)絡插件來支持。
- 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
上述規(guī)則意思如下:
入站
- default namespace下含有l(wèi)abel role=db的pod盼产,不滿足ingress和exgress的網(wǎng)絡訪問(出去瓤逼,進入)都會被拒絕
- default namespace下含有l(wèi)abel role=db的pod,172.17.0.0/16(除去172.17.1.0/24)的網(wǎng)絡可以訪問伞鲫,其他的都被拒絕
- default namespace下含有l(wèi)abel role=db的pod粘茄,在label為project=myproject的namespace下都能訪問到
+default namespace下含有l(wèi)abel role=db的pod,在default namespace下只有l(wèi)abel為role=frontend的pod能訪問 - ports 為只能訪問的port秕脓,不寫所有ports都能訪問
出站
- default namespace下含label為role=db的pod柒瓣,只能訪問10.0.0.0/24 ,對應port的目標
典型規(guī)則的配置
1.同namespace的pod吠架,入站規(guī)則為全部禁止
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
2.同namespace的pod芙贫,入站規(guī)則為全部開放:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
ingress:
- {}
3.同namespace的pod,出站規(guī)則為全部禁止
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Egress
4.同namespace的pod傍药,出站規(guī)則為全部開放
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all
spec:
podSelector: {}
egress:
- {}
policyTypes:
- Egress