Sobes.tech
Middle+

How to configure NetworkPolicy in Kubernetes to prevent pods from one namespace from interacting with pods from another namespace?

sobes.tech AI

Answer from AI

To restrict interaction between pods from different namespaces in Kubernetes, you can use a NetworkPolicy object with a namespaceSelector.

Example of a NetworkPolicy that allows incoming traffic only from pods within the same namespace and blocks all others:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-cross-namespace
  namespace: target-namespace
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector: {}  # Allow traffic only from pods within the same namespace

If you want to explicitly deny traffic from other namespaces, you can omit allow rules for them, as by default everything is denied if at least one NetworkPolicy is applied to the pods.

For more complex scenarios, you can use namespaceSelector, for example, to allow traffic only from certain namespaces:

from:
- namespaceSelector:
    matchLabels:
      name: allowed-namespace
  podSelector: {}

Thus, to completely prevent interaction between namespaces, it is enough to create a NetworkPolicy in each namespace that allows traffic only within that namespace.