How do Kubernetes NetworkPolicies isolate pod-to-pod network communication?
β Interview Prompt: Explain Kubernetes NetworkPolicy ingress/egress rules, default-deny posture, and CNI plugin requirements for zero-trust pod networking.
By default, all Kubernetes pods can freely communicate with all other pods in any namespace β no isolation. NetworkPolicies implement micro-segmentation β defining which pods can communicate with which.
Default Behavior (No NetworkPolicy):
All pods can reach all other pods β equivalent to a flat network.
NetworkPolicy β Declarative Firewall Rules:
NetworkPolicies are additive whitelist rules. If a Pod is selected by any NetworkPolicy, only traffic explicitly allowed by that policy is permitted.
Key Concepts:
Default-Deny Posture (Best Practice):
First apply a default-deny policy that blocks all ingress/egress, then selectively open only what's needed.
CNI Plugin Requirement:
NetworkPolicies are API objects β they require a CNI plugin that enforces them (Calico, Cilium, Weave). The default kubenet/flannel does NOT enforce NetworkPolicies.
Code Implementation Example
# Step 1: Default-deny ALL ingress and egress in 'app' namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: app
spec:
podSelector: {} # selects ALL pods in namespace
policyTypes:
- Ingress
- Egress
---
# Step 2: Allow API pods to receive traffic from frontend pods only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-api
namespace: app
spec:
podSelector:
matchLabels:
role: api # policy applies to API pods
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend # only frontend pods can reach API
ports:
- protocol: TCP
port: 3000
---
# Step 3: Allow API pods to reach PostgreSQL only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-api-to-postgres
namespace: app
spec:
podSelector:
matchLabels:
role: api
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
role: database
ports:
- protocol: TCP
port: 5432Start with default-deny NetworkPolicy then selectively whitelist traffic paths. Requires Calico/Cilium CNI β the default CNI does not enforce NetworkPolicies.