Dev.to Security 🔐 Cybersecurity 👁 0 📖 4 min read

Kubernetes Cookbook Part 11: Network Policies, the Firewall You Forgot to Turn On

Here's a scenario that should make you uncomfortable: in a default Kubernetes cluster, every pod can talk to every other pod. Your public-facing web app can reach the database directly. A random test container can poke t

Here's a scenario that should make you uncomfortable: in a default Kubernetes cluster, every pod can talk to every other pod. Your public-facing web app can reach the database directly. A random test container can poke the kubelet. If one pod gets compromised — and one will, eventually — the attacker lands in a network with zero internal walls.

Kubernetes has a built-in answer, and almost nobody turns it on: NetworkPolicy. It's a firewall for your pods, declared the same way you declare everything else. This is Part 11 of the Kubernetes Cookbook — and it's the one I wish I'd read before my first cluster grew past three apps.

The mental model: allow-all by default

The most important thing to understand: NetworkPolicy is opt-in, and doing nothing means allow everything. Applying zero network policies is not "no firewall" — it's "firewall with a permanent allow-all rule."

The moment you apply any NetworkPolicy to a pod, that pod flips from allow-everything to allow-only-what-the-policy-says. This is the same pattern as RBAC: Kubernetes never takes permissions away until you explicitly grant scoped ones.

One critical warning before the YAML: a NetworkPolicy is only as real as your CNI plugin. The API object exists on every cluster, but something has to enforce it — Calico, Cilium, and Weave do; some minimal CNIs silently ignore policies, and your pods stay wide open while you sleep soundly. Check your CNI's docs first. If you're running kind or a bare-metal kubeadm cluster with a minimal CNI, verify enforcement before trusting it.

Step one: default-deny everything

Start by denying all ingress in a namespace. Nothing changes functionally yet — until you add allow rules, which is exactly the discipline you want:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: production
spec:
  podSelector: {}        # applies to EVERY pod in the namespace
  policyTypes:
  - Ingress

podSelector: {} matching everything surprises people the first time. An empty selector means "all pods," not "no pods." To verify your CNI actually enforces this, run a quick test — spin up a busybox pod and curl another pod's IP. If the connection still succeeds, your CNI is ignoring policies. Better to learn that now than during an incident.

Step two: allow only the traffic you need

Now the useful part. Say you have web → api → database. The web pods should accept traffic from the ingress controller, the api should accept from web only, and the database should accept from api on 5432 only:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-accepts-web-only
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: web
    ports:
    - port: 8080
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: database-accepts-api-only
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: api
    ports:
    - port: 5432

The beauty here: from uses the same label selectors you already know from Deployments and Services. You're not learning a new identity system — you're pointing at pods the way Kubernetes already points at them.

Step three: don't forget egress — and DNS

Blocking inbound traffic is half the story. If a compromised pod can still curl anywhere on the internet, it can exfiltrate data happily. Lock down egress too:

spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
  - Egress
  egress:
  - {}   # still thinking about this one? see below

Here's the trap everyone hits — myself included, in the form of a database that mysteriously stopped resolving names: the moment you add an egress policy, DNS breaks. Pods talk to kube-dns on UDP 53 constantly, and a default-deny egress kills that too. You must explicitly allow DNS:

  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: kube-system
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    ports:
    - port: 53
      protocol: UDP
    - port: 53
      protocol: TCP

That namespaceSelector + podSelector combo restricts DNS to the actual kube-dns pods in kube-system — not just "any pod claiming to serve DNS." After that, add your specific egress rules (database → nothing, api → database and external APIs, and so on).

How I roll this out without an outage

Don't write default-deny for the whole namespace in week one — you'll spend the weekend debugging why monitoring "randomly" stopped working. This is the order that worked on my clusters:

  1. Observe first. Deploy policies in a permissive audit mindset: allow with to: [{}] / from: [{}] placeholders, and watch your traffic logs (Cilium has great flow visibility; Calico has flow logs) to learn what actually talks to what.
  2. Lock the crown jewels first. Database and anything holding secrets get strict ingress policies immediately — they're the highest-value targets and usually have the fewest legitimate clients.
  3. Egress last, service by service. Start with the database (should have almost no egress), then the API tier.
  4. Keep a break-glass path. A labeled "ops" namespace with wide-open access, documented in your runbook, saves you at 2 AM.

Common traps, quickly

  • podSelector is namespace-local. A policy selecting pods in namespace A can't reach pods in namespace B with a plain podSelector — you need namespaceSelector alone, or combined.
  • Not all CNIs support ipBlock consistently, and cloud load balancer health checks often need CIDR-based exceptions. Test before assuming.
  • The empty-selector confusion cuts both ways: podSelector: {} = all pods, but a policy with ingress: [] (empty list) = deny all ingress to selected pods. Subtle, brutal difference.

The bottom line

NetworkPolicy is the cheapest security upgrade in Kubernetes: no new tools, no agents, no license — just YAML you could write this afternoon. But it's defense that only exists if your CNI enforces it, and it only works if you actually roll it out. Start with default-deny-ingress on your most sensitive namespace today. The flat network you've been living in is a choice, and it's reversible.

In Part 12, we'll package all of this up properly with Helm — because copy-pasting eleven parts' worth of YAML by hand is its own kind of outage waiting to happen.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.