(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
testnamespace to accidentally send traffic to other services or databases inprodnamespace. - You host applications from different customers in separate Kubernetes namespaces and you would like to block traffic coming from outside a namespace.
Start a web service in namespace default:
$ kubectl run web --namespace=default --image=nginx --labels="app=web" --expose --port=80Save 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: {}$ kubectl apply -f deny-from-other-namespaces.yaml
networkpolicy "deny-from-other-namespaces" created"Note a few things about this manifest:
namespace: defaultdeploys it to thedefaultnamespace.- it applies the policy to ALL pods in
defaultnamespace as thespec.podSelector.matchLabelsis empty and therefore selects all pods. - it allows traffic from ALL pods in the
defaultnamespace, asspec.ingress.from.podSelectoris empty and therefore selects all pods.
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 outIt 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>$ 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