Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 519 of 8028. Security and ObservabilityFree lesson

Controlling Namespace Isolation with Network Policies

Define rules that restrict or permit cross-namespace traffic to ensure sensitive workloads remain isolated from less secure development environments.

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

  1. Namespace Labeling: For the namespaceSelector to 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.
  2. 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.
  3. 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.