NetworkPolicies (CKAD)
Every pod can reach every pod until you say otherwise. Select pods, isolate them, and allow back only the paths the shop needs.
An interactive Kubernetes lesson: 20 steps, about 32 minutes, on a live simulation in your browser.
The shop has three layers. Customers reach web through a NodePort. web calls api. api reads and writes orders in db, a Postgres pod on port 5432.
Three streams show that chain working: customers to web, web to api, api to db. That is every connection the application needs.
What you will learn
Everything can reach everything
- A shop in three tiers
- The forgotten pod dials the database: With no NetworkPolicy the pod network is flat: any pod can connect to any pod, on any port, in any namespace.
Select pods, then allow
- A first policy around the database: A policy selects pods and isolates them. Its rules are an allow-list: anything not listed is dropped.
- What about the other pods?: Isolation is per pod. A pod that no policy selects is as open as it was on day one.
- Blocked looks like a timeout: Timeout means something dropped the packet on the way. Refused means it arrived and nobody was listening. Policy only ever causes timeouts.
Who may come in
- Lock the api tier: Policy ports are pod ports. The Service port has been translated away before the policy ever sees the packet.
- A caller from another namespace: podSelector alone means: pods with this label in my namespace. To reach across namespaces you must name the namespace too.
- namespaceSelector: Policies only add up. There is no deny rule and no order: if any policy on the pod allows the connection, it is allowed.
- One dash changes the meaning: Same list item: namespace AND pod. Separate list items: this peer OR that peer. Count the dashes.
Deny by default
- Break it: default deny closes the shop
- Open the front door on purpose: No rules allows no one. One empty rule allows everyone. An empty podSelector selects every pod in the namespace.
Traffic going out
- Restrict what api may call: Deny egress and you have denied DNS. The first packet of almost every connection is a lookup on port 53.
- Allow DNS: A connection needs both ends to agree: egress rules on the pod that sends, ingress rules on the pod that receives.
- ipBlock: things that are not pods: Selectors describe pods. ipBlock describes addresses outside the cluster. Policies match on labels and IPs, never on hostnames.
When it breaks
- Break it: a label that matches nothing
- The CNI plugin is the enforcer: A NetworkPolicy is a request. The CNI plugin enforces it. If the plugin does not support policies, the object exists and changes nothing.
- Drill: find a namespace's labels
- Drill: test with a timeout
Recap & playground
- Cheat sheet
- Playground