Kubernetes network policies: default-deny, keep DNS up
Lock down pod-to-pod traffic with a default-deny NetworkPolicy, then re-allow DNS and the flows your apps actually need.
By default a Kubernetes cluster is a flat network: every pod can reach every other pod, in any namespace. A NetworkPolicy is the cluster's firewall, but it only takes effect once your CNI enforces it (Calico, Cilium, and most managed CNIs do). The safe pattern is default-deny, then allow — and the very first thing default-deny breaks is DNS, so we fix that in the same breath.
kubectl exec -n shop web-0 -- curl -s --max-time 3 db:5432(connected) — any pod can reach any podkubectl get networkpolicy -n shopNo resources found in shop namespace.convenient for you, and exactly what an attacker wantsStep 1: default-deny the namespace
This policy selects every pod (podSelector: {}) and allows no ingress or egress. Apply it and the namespace goes dark.
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: default-denynamespace: shopspec:podSelector: {}policyTypes: [Ingress, Egress]
Step 2: allow DNS back
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: allow-dnsnamespace: shopspec:podSelector: {}policyTypes: [Egress]egress:- to:- namespaceSelector: {}podSelector:matchLabels: { k8s-app: kube-dns }ports:- { protocol: UDP, port: 53 }- { protocol: TCP, port: 53 }
Step 3: allow only the flows you need
Now open the specific paths. This lets web pods reach db on 5432 — and nothing else can.
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: web-to-dbnamespace: shopspec:podSelector:matchLabels: { app: db }policyTypes: [Ingress]ingress:- from:- podSelector:matchLabels: { app: web }ports:- { protocol: TCP, port: 5432 }
Verify it actually denies
kubectl exec -n shop web-0 -- curl -s --max-time 3 db:5432web -> db:5432 OKkubectl exec -n shop test-0 -- curl -s --max-time 3 db:5432timed out — denied, as intendedAlways test the denied path too. A policy that allows the happy path but forgets to deny the rest is a policy that does nothing.
Go deeper in a courseKubernetes security & hardeningNetwork policy, RBAC, Pod Security and the rest of CKS, hands-on.View course