Kubernetes NetworkPolicy: Additive Rules, Default Deny, and Other Traps

Spin up a pod in a default Kubernetes cluster and it can reach every other pod in the cluster, plus most of your private network. That flat network is convenient and terrifying in equal measure — a single compromised pod can scan your database tier with nothing in the way. Kubernetes NetworkPolicy is the built-in answer, a layer 3/4 firewall expressed as a resource. But NetworkPolicy has a reputation for confusing people, and the reputation is earned: policies are additive rather than last-match-wins, isolation is per-direction, and a syntactically valid policy can do absolutely nothing if your CNI plugin doesn’t implement enforcement.

This post covers the semantics that actually trip people up: the isolation model, the selector rules, the DNS trap in default-deny egress, and a safe rollout sequence. Everything here follows from the official NetworkPolicy documentation, but organized the way you’d debug it at 2 a.m.

First: Does Anything Enforce This?

NetworkPolicy is just an API object. The API server happily stores it, kubectl apply succeeds, and — if your network plugin doesn’t support NetworkPolicy — nothing changes. Enforcement lives in the CNI plugin: Calico, Cilium, Antrea, Weave and others implement it; the plain flannel and kubenet setups do not. There is no warning, no event, no error. “I applied the policy and pods still talk” is almost always this.

Verify enforcement early — most CNIs expose a policy agent’s pods you can check, and the fastest sanity test is empirical: apply a deny-all policy to a test pod and confirm its traffic actually stops.

The Isolation Model: Two Independent Switches

Every pod has two isolation flags, evaluated independently: one for ingress, one for egress. By default both are off — pods are “non-isolated” and all traffic flows. A policy flips a flag on if it selects the pod and lists that direction in policyTypes. Here is the subtle part: policyTypes can be inferred. If a policy has an ingress section, Ingress isolation is implied; same for egress. A policy with selectors but empty sections denies everything in that direction.

Once a pod is isolated in a direction, the allow rules work as a union. Policies never conflict and there is no priority or ordering — if three policies select a pod, the allowed traffic is everything any of them allows. Deny does not exist as a rule type; you deny by isolating and then not allowing. If you’re used to firewall chains where order matters and first-match wins, this model inverts your instincts: adding more policies can only ever loosen what a pod can reach, never tighten it.

And both ends must agree. A connection from pod A to pod B is allowed only if A’s egress policy permits it and B’s ingress policy permits it. Either side refusing kills the connection — which means a default-deny applied to your database changes the debugging picture for every client namespace at once.

Default Deny Is a Policy With an Empty Rule Set

The base pattern for any zero-trust rollout is default-deny per namespace. It looks like this:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: payments
spec:
  podSelector: {}          # selects every pod in the namespace
  policyTypes:
    - Ingress
  # no ingress rules: isolate, allow nothing

Empty podSelector: {} means “all pods in this namespace” — and only this namespace. NetworkPolicy namespacing is a common surprise: pod selectors and pod selectors in rules never cross namespace boundaries by themselves; that requires namespaceSelector. From the moment this policy exists, no inbound connection reaches any pod in payments except traffic from the pod’s own node. Every legitimate client now needs an explicit allow policy.

Typical allow policies then look like:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-allow-from-api
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: postgres
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              team: platform
          podSelector:
            matchLabels:
              app: orders-api
      ports:
        - protocol: TCP
          port: 5432

The YAML Trap: One Dash Changes Everything

The snippet above encodes the most expensive syntax mistake in this whole feature. In the from list there is one element with two keys — namespaceSelector and podSelector at the same indentation. That means: pods matching app: orders-api inside namespaces matching team: platform. An intersection.

Add one dash and the meaning changes completely:

    - from:
        - namespaceSelector:
            matchLabels:
              team: platform
        - podSelector:
            matchLabels:
              app: orders-api

Now from has two elements: all pods in platform namespaces, or pods labeled app: orders-api in the policy’s own namespace. A union instead of an intersection — and likely a much wider hole than intended. Because YAML indentation differences like this are invisible to review at a glance, make kubectl describe networkpolicy part of your workflow; it prints how the API server parsed the policy, and the interpreted output makes the mistake obvious.

Default-Deny Egress Breaks DNS First

The egress version of default-deny comes with the official documentation’s own caution: it blocks DNS. The moment your pods are isolated for egress, every lookup of orders-api.payments.svc.cluster.local fails, and the failure surfaces as weird application timeouts rather than obvious policy errors. Always allow DNS explicitly:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: payments
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

The kubernetes.io/metadata.name label exists on every namespace by default (stable since v1.22) precisely so you can target namespaces without adding custom labels. Allow both UDP and TCP on port 53 — DNS falls back to TCP for large responses, and policies that only allow UDP produce intermittent, size-dependent failures that are miserable to diagnose.

Similar reasoning applies to anything in the pod’s traffic path: metrics scraping (allow ingress from the Prometheus pods), service mesh proxies (policies select pods, and sidecar traffic is still pod-to-pod traffic), egress to your container registry, and webhook callbacks.

ipBlock: Weaker Than It Looks

Besides pod and namespace selectors, rules can use ipBlock CIDR ranges to allow external addresses. Two caveats from the spec itself. First, Pod IPs are ephemeral, so ipBlock is meant for cluster-external ranges — using it for in-cluster peers is a bug waiting for a reschedule. Second, ingress controllers and SNAT gateways rewrite packet IPs, and the spec explicitly leaves it undefined whether rewriting happens before or after policy evaluation; depending on plugin and cloud provider, the “source” your ipBlock rule sees may be a load balancer address, not the real client. Treat ipBlock rules as approximations and verify empirically on your stack.

A Safe Rollout Sequence

NetworkPolicies combine additively, which makes them unusually safe to roll out gradually:

  • Audit first. Run a policy-recommendation tool or watch existing flows to learn what each namespace actually talks to.
  • Apply default-deny ingress to one namespace. Not the cluster — one namespace with an on-call owner watching.
  • Add allow policies until traffic works, confirming each with kubectl describe networkpolicy and real probes rather than assumptions.
  • Then add default-deny egress plus DNS, which is the step that surfaces all the hidden dependencies: metrics, tracing, registry pulls, SMTP.
  • Repeat per namespace. Namespaces without any policy remain fully open — the default-deny in one namespace does nothing for its neighbors.

NetworkPolicy is not a service mesh, and it won’t give you identity, encryption, or layer 7 rules. But it is a huge fraction of the practical security win for very little cost: a default-deny posture plus a handful of explicit allow lists collapses the blast radius of a compromised pod from “the whole cluster” to “the namespace, minus what you deliberately opened.”

Leave a Reply

Your email address will not be published. Required fields are marked *