K8s by Example: Network Policies
| NetworkPolicies are firewall rules for Pods. By default, all Pods can communicate freely. Policies restrict traffic to explicit allow rules. Requires a CNI that supports NetworkPolicy (Calico, Cilium, etc.). |
| network-policy.yaml | |
| NetworkPolicies use the | |
| network-policy-ingress.yaml | |
| Ingress rules control incoming traffic. This example allows traffic from frontend Pods on port 8080. Empty selector | |
| network-policy-logic.yaml | |
| Multiple selectors in one | |
| network-policy-namespace.yaml | |
| Allow traffic from other namespaces using | |
| network-policy-egress.yaml | |
| Control egress (outbound) traffic. First rule allows DNS (port 53), which is critical or Pods can’t resolve names. Second rule allows external HTTPS except private IPs. Use | |
| default-deny.yaml | |
| Default deny policies isolate a namespace. Apply these first, then add specific allow rules. Best practice for multi-tenant clusters and zero-trust networking. | |
| network-policy-ports.yaml | |
| Named ports reference container port names instead of numbers. More maintainable when port numbers change. Use | |
| terminal | |
| Debug NetworkPolicies by checking which policies apply to a Pod and verifying CNI support. Policies are additive, so if any policy allows traffic, it’s allowed. | |