Network Policies
NetworkPolicy is Kubernetes’ built-in L3/L4 firewall object. It only works if your CNI enforces policies (Calico, Cilium, AWS VPC CNI policy mode, etc.).
Default deny vs allow lists
Section titled “Default deny vs allow lists”- Default deny — start from a policy that selects all pods in a namespace (or tenant) and allows no traffic; then add explicit ingress/egress rules. This is the practical shape of least privilege.
- Selective allow lists — each rule names who can talk to whom on which ports; combine ingress and egress for defense in depth.
Default deny example (namespace-wide)
Section titled “Default deny example (namespace-wide)”Deny all ingress to every pod in team-a (adjust podSelector as needed):
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: default-deny-ingress namespace: team-aspec: podSelector: {} policyTypes: [Ingress]Then add per-app policies that allow only required sources.
Egress: block cloud instance metadata (AWS example)
Section titled “Egress: block cloud instance metadata (AWS example)”Block the link-local metadata endpoint for selected pods:
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: deny-metadata namespace: team-aspec: podSelector: matchLabels: tier: app policyTypes: [Egress] egress: - to: - ipBlock: cidr: 0.0.0.0/0 except: - 169.254.169.254/32Validate semantics with your CNI — some teams prefer explicit allow egress lists instead of broad 0.0.0.0/0 with exceptions.
Testing with netshoot
Section titled “Testing with netshoot”kubectl run netshoot --rm -it --image=nicolaka/netshoot -n team-a -- bash# inside: curl -v http://service.otherns.svc.cluster.localIf traffic should be denied but succeeds, your CNI likely does not enforce policies.
CNI compatibility (high level)
Section titled “CNI compatibility (high level)”| CNI | Policy support notes |
|---|---|
| Calico | Long-standing policy engine; policy-only mode with other CNIs possible |
| Cilium | Rich L3/L4/L7; eBPF datapath |
| AWS VPC CNI | Check VPC CNI Network Policy feature for eBPF enforcement |
| Flannel (vanilla) | Often no enforcement — pair with Calico policy-only or migrate CNI |
Related
Section titled “Related”- Networking — Services, DNS, and a selective policy example.
- Multi-tenancy and policy — Tenant isolation beyond netpol.
- Architecture review answers — Prompts this page deepens.