How do NetworkPolicies enforce micro-segmentation in Kubernetes, and what CNI requirements must be met for them to work?
Quick Answer
NetworkPolicies are firewall rules selecting Pods by labels and defining allowed ingress/egress peers (Pods, namespaces, CIDR blocks). They are deny-by-default only when a CNI implements them (Calico, Cilium, Weave). Without a supporting CNI, NetworkPolicy objects are no-ops.
Detailed Answer
By default, Kubernetes allows any Pod to communicate with any other Pod on any port—a flat network. NetworkPolicy introduces opt-in segmentation: once a Pod is selected by a NetworkPolicy, it enters an isolated mode where only explicitly permitted traffic is allowed. Pods not selected by any policy continue to accept all traffic (depending on CNI default-deny namespace settings).
A NetworkPolicy spec contains podSelector (which Pods the rules apply to), policyTypes (Ingress, Egress, or both), and rule lists. Ingress rules define who may connect to selected Pods and on which ports. Egress rules define where selected Pods may connect. Peers can be other Pods (via label selectors), namespaces (namespaceSelector), or IP blocks (ipBlock with optional except CIDR exclusions).
For user-auth-service in the auth namespace, you might allow ingress only from payments-api in the production namespace on port 8443, and egress only to an external identity provider at a specific CIDR on port 443. checkout-worker in the jobs namespace would be denied direct access to user-auth-service, limiting lateral movement if a worker Pod is compromised.
Critical operational detail: NetworkPolicies require a CNI that enforces them. Flannel's default mode does not. Calico, Cilium, and Weave Net implement enforcement via eBPF, iptables, or proprietary dataplanes. Always verify enforcement in staging before assuming policies protect production.
Analogy: NetworkPolicy is like office badge access. Without a policy, everyone can enter every room. Once you assign a badge rule to the finance team (Pod), only people from approved departments (peer selectors) can enter finance rooms on specified doors (ports). Unlisted visitors are turned away at the door.
Combine NetworkPolicies with namespace-per-team boundaries, deny-all default policies in sensitive namespaces, and explicit allow lists for each service. Test with netcat or kubectl debug pods from unauthorized namespaces to validate enforcement.
Document policies in runbooks and version-control them alongside application manifests. When rolling out to production, apply default-deny egress only after confirming DNS and image-registry paths are allowed—otherwise Pods fail silently on pull or lookup. Cilium NetworkPolicy supports HTTP path rules at L7, bridging toward service-mesh granularity without a full sidecar deployment.