How do you restrict pod-to-pod communication in Kubernetes?
Quick Answer
Use NetworkPolicies. Apply a default-deny policy for a namespace, then add allow rules selecting the specific namespaces, pods, or labels that are permitted — the CNI plugin enforces them.
Detailed Answer
NetworkPolicies are namespaced and select pods by label; you define ingress/egress rules by podSelector, namespaceSelector, and ipBlock. A common pattern is a default-deny-all policy plus targeted allows (for example only the frontend may reach the backend on port 8080). They require a CNI that supports them (Calico, Cilium); on some CNIs they are a no-op.
Code Example
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
spec:
podSelector: {}
policyTypes: ["Ingress"] # default-deny all ingress in this namespaceInterview Tip
Lead with default-deny then explicit allow, and note it only works if the CNI supports NetworkPolicy.