Isolate pods in a namepace from other namespaces using network policy

4/22/2021

Is there a way to isolate one namespace from accessing other namespace but still be able to go outside the cluster I have 10 namespaces, I want that pods within this 1 namespace are not be able to talk to other namespaces but still be able to go outside the cluster to external resources while this is applied to only 1 namespace the other 9 namespaces can talk to each other

-- user3805888
kubernetes
kubernetes-networkpolicy

1 Answer

4/22/2021

Try this one

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  namespace: default //your 1 namespaces on which you want to deny all traffic.
  name: deny-from-other-namespaces
spec:
  podSelector:
    matchLabels:
  ingress:
 - from:
    - podSelector: {}

Note a few things about this manifest:

  • namespace: default deploys it to the default namespace.Please change it as per your need.
  • It applies the policy to ALL pods in default namespace as the
    spec.podSelector.matchLabels is empty and therefore selects all pods.
  • It allows traffic from ALL pods in the default namespace, as
    spec.ingress.from.podSelector is empty and therefore selects all pods. Here is an awesome on network policy github repo from which i have taken this example.
-- Taybur Rahaman
Source: StackOverflow