CKA [Installation] – NetworkPolicy例子5,NamespaceSelector的使用

根据这个例子,比如你有多个namespace,但是在production namespace 你只允许Security namespace访问而已,其他所有的namespace都无权访问。

✅ 实验案例

1. 创建NetworkPolicy , 这个policy是在production namespace而且并无podSelector 所以涵盖了整个production namespace所有的pod

kubectl create ns production
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: example-5
namespace: production
spec:
podSelector: {}
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: security
policyTypes:
- Ingress
kubectl apply -f netpol.yaml

2. 根于以上的yaml我选择的是 kubernetes.io/metadata.name: security , 你可以使用这个命令行来获取

kubectl get ns --show-labels

2. 在production namespace创建production-pod

kubectl run production-pod -n production --image=alpine/curl -- sleep 36000

3. 创建security namespace 和 security-pod

kubectl create ns security
kubectl run security-pod -n security --image=alpine/curl -- sleep 36000

4. 在default namespace创建 test-pod

kubectl run test-pod -n default --image=alpine/curl -- sleep 36000

5. 查看production-pod的ip

kubectl get pods -A -o wide

6. 进入security-pod 和 test-pod 内,然后去ping production-pod的ip

kubectl exec -it security-pod -n security -- sh
kubectl exec -it test-pod -n default -- sh
ping 10.244.120.76

你会看到security-pod ping得到,而test-pod ping不到

Loading

Facebook评论