k8s network policy for namespace networkings isolation to multi-tenacy scene
network policy可以帮助我们很好的解决k8s中的网络隔离,对于多租户场景,可以每一个用户一个名字空间,然后对这个名字空间设置网络隔离
network policies
- https://kubernetes.io/docs/concepts/services-networking/network-policies/
- https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/
By default, pods are non-isolated; they accept traffic from any source.
Pods become isolated by having a NetworkPolicy that selects them. Once there is any NetworkPolicy in a Namespace selecting a particular pod, that pod will reject any connections that are not allowed by any NetworkPolicy. (Other pods in the Namespace that are not selected by any NetworkPolicy will continue to accept all traffic.)
为用户user1创建名字空间,名字空间与用户名同名
apiVersion: v1
kind: Namespace
metadata:
name: user1
labels:
org: user1
project: user1_project
给名字空间user1的annotation isolation: DefaultDeny
kubectl annotate ns user1 "net.beta.kubernetes.io/network-policy={\"ingress\": {\"isolation\": \"DefaultDeny\"}}" --overwrite
我们假定user1创建的pod都带有label
org: user1
这样为名字空间user1创建network-policy
kind: NetworkPolicy
apiVersion: extensions/v1beta1
metadata:
name: access-user1_project
namespace: user1
spec:
podSelector:
matchLabels:
org: user1
ingress:
- from:
- podSelector:
matchLabels:
access: "true"
- namespaceSelector:
matchLabels:
project: user1_project
- 如此,只要user1空间中的资源 访问user1的资源, 从其他名字空间访问不了user1中的资源
- 目前network policy只有ingress的