Kubernetes Network Policies
NetworkPolicy spec, ingress/egress rules, podSelector and namespaceSelector, and CNI support (Calico/Cilium).
Overview
Overview Kubernetes NetworkPolicy resources define rules for how pods can communicate with each other and with endpoints outside the cluster. By default, Kubernetes applies no network isolation — all pods can communicate with all other pods regardless of namespace. NetworkPolicy is the mechanism for implementing Zero Trust microsegmentation within a Kubernetes cluster.
A NetworkPolicy applies to a set of pods (selected by a podSelector label query) and defines which inbound (ingress) and outbound (egress) traffic is allowed. Once at least one NetworkPolicy selects a pod, that pod's traffic is restricted to what the policies explicitly allow — unmatched traffic is denied. A pod with no NetworkPolicy selecting it remains unrestricted.
The NetworkPolicy spec has three key selectors: podSelector (which pods this policy applies to), ingress rules (inbound traffic — from which pods/namespaces/CIDR blocks), and egress rules (outbound traffic — to which pods/namespaces/CIDR blocks). Each ingress or egress rule can specify a combination of podSelector, namespaceSelector, and ipBlock.
A critical implementation detail: NetworkPolicy is enforced by the CNI (Container Network Interface) plugin, not by the Kubernetes control plane itself. The default CNI plugins (Flannel, kubenet) do not enforce NetworkPolicy — they simply ignore the resources. You must use Calico, Cilium, Weave Net, or Antrea. If you apply NetworkPolicy rules without a supporting CNI, the policies exist in the API server but have no effect.
Calico implements NetworkPolicy using iptables rules on each node. It also provides GlobalNetworkPolicy (cluster-wide policies) and host endpoint policies. Cilium implements NetworkPolicy using eBPF programs, achieving higher performance and adding L7-aware policies (HTTP path and method matching) that standard NetworkPolicy cannot express.
Key concepts
- Default deny vs default allow
- podSelector
- namespaceSelector
- CNI enforcement requirement
- Cilium L7 policy
Interview questions
- Write Kubernetes NetworkPolicy resources to implement a three-tier isolation: frontend can talk to backend, backend can talk to database, no other pod-to-pod traffic allowed.
- What is the difference between Calico and Cilium for NetworkPolicy enforcement, and when would you choose Cilium?
Sign up free to read the full topic
More Networking topics
Start free on Cariara · Coding problems · System design studio