Namespace Selectors
What You'll Learn
You'll learn how to use namespaceSelector in NetworkPolicies to control traffic based on which namespace pods live in, not just which labels they have.
The Core Idea
Until now, you've used label selectors to choose which pods can send or receive traffic. But what if you want to allow traffic from all pods in a specific namespace, regardless of their individual labels?
That's where namespaceSelector comes in. It lets you write rules like "allow traffic from any pod in the frontend namespace" or "block everything from the untrusted namespace."
How It Works
Think of namespaces like buildings in a campus. Instead of listing every person (pod) allowed through your door, you can say "anyone from the Engineering building can enter." That's namespaceSelector—you're filtering by namespace, not individual pod identity.
In your NetworkPolicy, you add a namespaceSelector field to your ingress or egress rules:
namespaceSelector:
matchLabels:
environment: production
This selects namespaces that have the label environment: production. Any pod in those namespaces can communicate according to your rule.
Combining Selectors
You can use namespaceSelector alone, or combine it with podSelector in the same rule. When both appear together, both conditions must match—the pod must be in the right namespace and have the right labels.
Common Use Case
Imagine you want your database pods to only accept connections from pods in your backend namespace. You'd create a NetworkPolicy on the database pods with an ingress rule using namespaceSelector to match backend.
Key Takeaway:
namespaceSelector filters traffic by namespace membership, letting you allow or deny communication based on namespace labels rather than individual pod labels.