Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Kubernetes NetworkPolicies: Ingress, Egress, and the AND/OR Selector Trap

Policies are additive allow-lists with no deny rules. How one indentation level turns an airtight namespace rule into a cluster-wide hole, and why DNS breaks after default-deny.

~5 min readKubernetes
#Kubernetes#NetworkPolicy#Networking#Security
3D illustration of pod cubes inside a fenced boundary with allow-list arrows through gated walls

Quick Summary

A NetworkPolicy is a namespaced, label-based firewall for pods. It selects pods with podSelector and declares which traffic is allowed in (ingress) and out (egress). The rule that surprises everyone: policies are additive allow-lists. A pod selected by any policy for a direction has that direction default-denied, and only matching rules permit traffic. There are no deny rules — the way to deny is to omit.

Three conditions must hold for traffic to pass: the destination pod is selected by a policy whose ingress matches the source, the source pod is selected by a policy whose egress matches the destination (if egress is enforced), and the CNI plugin in the cluster actually implements NetworkPolicy. Flannel alone does not; Calico, Cilium, Antrea, and most managed CNIs do.

Namespaces are labels too. namespaceSelector selects whole namespaces by label, podSelector selects pods in the policy's own namespace, and combining them in one from element is an AND, while listing them as separate elements is an OR — the detail that makes a rule either airtight or wide open.

Basic Syntax & Core Signatures

yaml
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: api-allow-web namespace: shop spec: podSelector: matchLabels: { app: api } policyTypes: [Ingress, Egress] # omitted => Ingress only (or Egress if egress rules exist) ingress: - from: - namespaceSelector: matchLabels: { kubernetes.io/metadata.name: shop } podSelector: matchLabels: { app: web } # AND: pods of app=web in namespace shop ports: - protocol: TCP port: 8080 - protocol: TCP port: 9000 endPort: 9010 # range, needs endPort support egress: - to: - namespaceSelector: matchLabels: { kubernetes.io/metadata.name: kube-system } podSelector: matchLabels: { k8s-app: kube-dns } ports: - { protocol: UDP, port: 53 } - { protocol: TCP, port: 53 } - to: - namespaceSelector: matchLabels: { kubernetes.io/metadata.name: data } ports: - { protocol: TCP, port: 5432 }
yaml
# Default deny for every pod in the namespace: select all, allow nothing apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny-all namespace: shop spec: podSelector: {} policyTypes: [Ingress, Egress]
bash
kubectl -n shop get networkpolicy # NAME POD-SELECTOR AGE # default-deny-all <none> 3d # api-allow-web app=api 3d kubectl -n shop describe networkpolicy api-allow-web kubectl get pods -n shop --show-labels kubectl get ns --show-labels

Key Comparison Table

FieldSelectsScope
podSelector (top level)Pods the policy applies toOwn namespace only
ingress.from[].podSelectorSource podsOwn namespace only
ingress.from[].namespaceSelectorSource namespaces by labelAll pods in matching namespaces
Both in one from entrySource pods in matching namespacesAND
Separate from entriesEither sourceOR
ipBlockCIDR rangesWith except for carving holes
BehaviourRule
No policy selects a podAll traffic allowed
One policy selects it for IngressOnly listed ingress allowed
Several policies select itRules add up (union of allows)
policyTypes omittedIngress implied; Egress implied only if egress rules exist
Empty podSelector: {}Every pod in the namespace
No ports in a ruleAll ports from that source
No from in an ingress ruleAll sources
Explicit denyNot expressible; omit instead
SymptomMeaning
Traffic blocked with no policyAnother policy selects the pod
Egress enforced, DNS failsNo egress rule to kube-system on port 53
Rule has no effectCNI does not implement NetworkPolicy
503 from a ServicePods reachable by the client but not by the proxy path, or vice versa

Practical Edge Cases & Deep Dives

1. AND versus OR in from — one indentation level decides everything

yaml
from: - namespaceSelector: { matchLabels: { env: prod } } podSelector: { matchLabels: { app: web } } # prod namespaces AND app=web --- from: - namespaceSelector: { matchLabels: { env: prod } } # any pod in prod namespaces - podSelector: { matchLabels: { app: web } } # OR any app=web pod in this namespace

These two blocks look nearly identical and are not. The first permits only pods labelled app=web inside namespaces labelled env=prod. The second permits everything in prod namespaces plus every app=web pod in the policy's own namespace — which in a shared cluster is usually a hole. Ingress controllers and monitoring are the usual accidental beneficiaries.

2. Default deny that does not lock you out

yaml
# Order does not matter: this is additive with the allow policies above spec: podSelector: {} policyTypes: [Ingress, Egress]

Apply default-deny-all to a namespace and every pod in it loses all traffic except what other policies allow — including DNS, which breaks service discovery silently (the app resolves nothing, or resolves slowly). The minimum egress for any namespace is DNS to kube-system, plus a route to whatever it calls. Note that a pod's own traffic to itself (localhost) and to the node it runs on is unaffected by NetworkPolicy in most implementations.

When rolling this out: enable policyTypes: [Ingress] first, watch, then add egress. Deploy policies alongside the workload in the same manifest so a namespace never exists in a half-configured state.

3. ipBlock, node CIDRs, and traffic that never reaches the pod network

yaml
ingress: - from: - ipBlock: cidr: 10.0.0.0/8 except: - 10.244.0.0/16 # carve out the pod CIDR ports: [{ protocol: TCP, port: 443 }]

ipBlock matches packet source addresses, and for traffic arriving from outside the cluster that can be the node IP (with externalTrafficPolicy: Cluster), a load balancer address, or the real client IP (externalTrafficPolicy: Local). kube-proxy's SNAT changes which of those you see, so an ipBlock rule that worked in staging can stop matching after a Service change. Health checks from the cloud load balancer are the classic case: they come from node IPs or a documented LB range, never from the pod network.

Traffic to the API server is not governed by NetworkPolicy; kube-apiserver and kubelet traffic is outside the CNI's enforcement path in most distributions.

4. Named ports, endPort, and protocol details

ports[].port accepts a number or a named port that matches a container port name, and endPort turns a single entry into an inclusive range. Protocol defaults to TCP; UDP and SCTP are allowed. Rule matching is on the destination port for ingress and the destination port for egress — meaning an egress rule to a service on 443 is written as 443 even if the server answers from an ephemeral source port, because policy is evaluated on the initial packet.

yaml
ports: - { protocol: TCP, port: 8080, endPort: 8085 } - { protocol: UDP, port: 53 }

5. Policies are namespaced; ingress controllers and cross-namespace access are not

A NetworkPolicy only selects pods in its own namespace. To allow an ingress controller running in ingress-nginx to reach pods in shop, you write the policy in shop with a namespaceSelector matching the controller's namespace label. The controller's own policy is irrelevant.

bash
kubectl get ns ingress-nginx --show-labels # kubernetes.io/metadata.name=ingress-nginx,... (automatic since 1.21)

Every namespace created since Kubernetes 1.21 carries kubernetes.io/metadata.name=<name> as an immutable label, so namespaceSelector on that label needs no manual labelling. Rely on it instead of inventing a label scheme that new namespaces will not get.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Policy applied, traffic still flowsCNI does not enforce NetworkPolicyVerify the CNI (Calico/Cilium/Antrea)
Traffic blocked unexpectedlyA default-deny in the namespaceRead all policies selecting the pod
DNS breaks after egress policyNo UDP/TCP 53 egress ruleAllow kube-system DNS on 53
Ingress controller gets 503Controller namespace not allowednamespaceSelector on the controller namespace
Health checks failipBlock does not match node/LB IPsAllow the node CIDR or LB range
Rule "works in staging"Different SNAT from externalTrafficPolicyMatch the actual source addresses
Only some pods affectedpodSelector matches fewer labels than intendedkubectl get pods --show-labels
Cross-namespace rule ignoredPolicy written in the wrong namespacePolicy belongs to the destination namespace
Egress to a Service name failsPolicy matches IPs after resolutionAllow the endpoint CIDR range
Metrics/logs stop after rolloutMonitoring namespace not allowedAdd monitoring to the allow list

A NetworkPolicy answers one question per pod and direction: "which peers may talk to me?" Every mistake above is a mismatch between what the author pictured and what the selector actually selected. Dump the pod's labels, dump every policy in the namespace, and check the CNI last.

Try matching browser tools

All tools

Small utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Kubernetes guides

More in Kubernetes

All Kubernetes guides

The guides filed next to this one in Kubernetes, in library order.