deny-traffic-from-other-namespaces
# DENY all traffic from other namespaces
(a.k.a LIMIT access to the current namespace)
You can configure a NetworkPolicy to deny all the traffic from other namespaces while allowing all the traffic coming from the same namespace the pod deployed to.
Use Cases
- You do not want deployments in
test
namespace to accidentally send traffic to other services or databases inprod
namespace. - You host applications from different customers in separate Kubernetes namespaces and you would like to block traffic coming from outside a namespace.
# Example
Start a web service in namespace default:
$ kubectl run web --namespace=default --image=nginx --labels="app=web" --expose --port=80
1
Save the following manifest to deny-from-other-namespaces.yaml
and apply
to the cluster:
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
namespace: default
name: deny-from-other-namespaces
spec:
podSelector:
matchLabels:
ingress:
- from:
- podSelector: {}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
$ kubectl apply -f deny-from-other-namespaces.yaml
networkpolicy "deny-from-other-namespaces" created"
1
2
2
Note a few things about this manifest:
namespace: default
deploys it to thedefault
namespace.- it applies the policy to ALL pods in
default
namespace as thespec.podSelector.matchLabels
is empty and therefore selects all pods. - it allows traffic from ALL pods in the
default
namespace, asspec.ingress.from.podSelector
is empty and therefore selects all pods.
# Try it out
Query this web service from the foo
namespace:
$ kubectl create namespace foo
$ kubectl run test-$RANDOM --namespace=foo --rm -i -t --image=alpine -- sh
/ # wget -qO- --timeout=2 http://web.default
wget: download timed out
1
2
3
4
2
3
4
It blocks the traffic from foo
namespace!
Any pod in default
namespace should work fine:
$ kubectl run test-$RANDOM --namespace=default --rm -i -t --image=alpine -- sh
/ # wget -qO- --timeout=2 http://web.default
<!DOCTYPE html>
<html>
1
2
3
4
2
3
4
# Cleanup
$ kubectl delete pod web -n default
$ kubectl delete service web -n default
$ kubectl delete networkpolicy deny-from-other-namespaces -n default
$ kubectl delete namespace foo
1
2
3
4
2
3
4
上次更新: 2024/02/26, 10:14:04