Hey it’s been a while trying to block traffic from other namespaces and only access pods in same namespace, I looked over many threads but none work! What I tried so far is:
I created a globalnetworkpolicy using calico to allow egress traffic:
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: allow-all-egress
spec:
egress:
- action: Allow
destination: {}
source: {}
order: 100
selector: all()
types:
- Egress
- created two namespaces:
kubectl create ns policy-demo1
kubectl create ns policy-demo2
- applied following networkpolicy in each namespace to enable ingress only in each namespace:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all-ingress
namespace: policy-demo1
spec:
podSelector: {}
ingress:
- {}
policyTypes:
- Ingress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all-ingress
namespace: policy-demo2
spec:
podSelector: {}
ingress:
- {}
policyTypes:
- Ingress
- created in each namespace an nginx server and a busybox to test:
# for namespace: policy-demo1
kubectl create deployment --namespace=policy-demo1 nginx --image=nginx
kubectl expose --namespace=policy-demo1 deployment nginx --port=80
kubectl run --namespace=policy-demo1 access --rm -ti --image busybox /bin/sh
# did same for namespace policy-demo2
The wget -q --timeout=5 nginx -O -
and ping <IP_of_nginx_pod>
works as expected in same namespace. However when I ping nginx container that lives in policy-demo1
from policy-demo2
it works, which I don’t want this behavior. Want to block traffic comming from different namespaces.
I tried another networkpolicy and added namespaceSelector
:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all-ingress
namespace: policy-demo1
spec:
podSelector: {}
ingress:
- from:
- namespaceSelector:
matchLabels:
name: policy-demo1 # added this label to policy-demo namespace
policyTypes:
- Ingress
but pinging or doing wget
from busybox image to nginx in the same namespace stopped working, what am I doing wrong please?
Thank you.
2
Answers
Could it be the fact that in the
namespaceSelector
, you specifiedpolicy-demo1
instead ofpolicy-demo2
?instead of
You should address both ingress and egress in your NetworkPolicy to get the results you desire.
Here’s all you need –
Create this NetworkPolicy in namespace policy-demo1:
Create this NetworkPolicy in namespace policy-demo2:
The pods in policy-demo1 can now only communicate with pods in policy-demo1. Same applies for pods in policy-demo2.
You can remove your GlobalNetworkPolicy and any other NetworkPolicy objects.