Skip to content

Network Policies

First PublishedByAtif Alam

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 — 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.

Deny all ingress to every pod in team-a (adjust podSelector as needed):

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: team-a
spec:
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/v1
kind: NetworkPolicy
metadata:
name: deny-metadata
namespace: team-a
spec:
podSelector:
matchLabels:
tier: app
policyTypes: [Egress]
egress:
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32

Validate semantics with your CNI — some teams prefer explicit allow egress lists instead of broad 0.0.0.0/0 with exceptions.

Terminal window
kubectl run netshoot --rm -it --image=nicolaka/netshoot -n team-a -- bash
# inside: curl -v http://service.otherns.svc.cluster.local

If traffic should be denied but succeeds, your CNI likely does not enforce policies.

CNIPolicy support notes
CalicoLong-standing policy engine; policy-only mode with other CNIs possible
CiliumRich L3/L4/L7; eBPF datapath
AWS VPC CNICheck VPC CNI Network Policy feature for eBPF enforcement
Flannel (vanilla)Often no enforcement — pair with Calico policy-only or migrate CNI