Skip to content

Network policies

Draft: not yet run against a live cluster. Treat output as representative and check it on yours.

NetworkPolicies are the main way to segment traffic inside a cluster, and the least intuitive API in core Kubernetes. Three rules explain almost every surprise.

  1. The API server stores the policy. It validates the syntax but has no idea whether anything will enforce it.

  2. The CNI’s agent on each node watches policies, pods, and namespaces. It translates selectors into the current set of pod IPs and programs filters (iptables, nftables, or eBPF, depending on the CNI).

  3. Selectors are re-evaluated continuously. A new pod with matching labels is covered as soon as the agent sees it. A namespace selector matches namespace labels, so every namespace automatically carries kubernetes.io/metadata.name: <name> to select it by name.

  4. Policies are stateful for allowed connections. If ingress to a server is allowed, the reply traffic doesn’t need a separate egress rule on the server.

kind’s default CNI doesn’t enforce NetworkPolicies. Create the cluster with the default CNI disabled and install one that does, such as Calico or Cilium, following that project’s kind instructions. Then:

default-deny.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: shop
spec:
podSelector: {} # every pod in the namespace
policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
namespace: shop
spec:
podSelector: {}
policyTypes: [Egress]
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 }

Apply only default-deny first and try a lookup from a pod in shop: it times out. Apply allow-dns and it works again. Note that namespaceSelector and podSelector are in the same list item, which means “pods with this label in namespaces with this label.” Split into two items, they would mean “either.”

A namespace has no NetworkPolicies. Is traffic to its pods allowed?

Yes. Without any selecting policy, pods accept all traffic.

After an egress default-deny, a pod can't reach a Service in its own namespace by name. What else must you allow?

DNS: egress to CoreDNS in kube-system on UDP and TCP port 53. Then an egress rule to the Service’s pods, and a matching ingress rule on the server side if it’s also default-deny.

What's the difference between namespaceSelector and podSelector in one 'from' item versus two items?

In one item they’re combined with AND (these pods in these namespaces). In two items they’re OR (these pods in this namespace, or any pod in those namespaces).

Maps to: CKA: Services and Networking; CKAD: Services and Networking. Check the current exam curriculum, since domain names change between revisions.