In this lesson, you will learn how to enforce security boundaries between namespaces using NetworkPolicy objects to prevent unauthorized cross-namespace communication.
By default, Kubernetes implements a flat network model where any pod can communicate with any other pod in the cluster, regardless of their namespace. While convenient for development, this poses a security risk in production, where a compromised pod in a dev namespace could potentially reach sensitive services in a prod namespace. To mitigate this, we use NetworkPolicy resources to explicitly whitelist allowed traffic paths.
Cross-Namespace Isolation via Selectors
To restrict access across namespaces, we use a policy that filters traffic based on both the namespaceSelector and the podSelector. When you apply a policy to a namespace, you are telling the CNI (Container Network Interface) to drop any traffic that doesn't meet your defined criteria.
Consider a scenario where we want to allow our frontend pods in the production namespace to talk to backend pods in the same namespace, but strictly forbid any ingress from the development namespace.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: allow-prod-only
namespace: production
spec:
podSelector:
matchLabels:
app: backend
ingress:
- from:
- namespaceSelector:
matchLabels:
environment: production
podSelector:
matchLabels:
app: frontend
Key Considerations
- Namespace Labeling: For the
namespaceSelectorto function, the target namespaces must have matching labels. You must label your namespaces (e.g.,kubectl label namespace production environment=production) before the policy can identify them. - Policy Enforcement: Network policies are additive. If you have a "Default Deny All" policy active, ensure your cross-namespace policies explicitly allow the necessary traffic, or the pods will be unable to communicate.
- Implicit Deny: If a pod is selected by any
NetworkPolicy, it becomes isolated. Any traffic not explicitly allowed by a policy will be dropped, effectively creating an "allow-list only" security posture for your sensitive workloads.
Key Takeaway: By using namespaceSelector within your NetworkPolicy ingress rules, you can create strict logical boundaries that prevent lateral movement between disparate environments, even within the same cluster.