Isolate the pods of a namespace with NetworkPolicies: deny everything by default, then allow only the needed flows, in ingress and in egress.
The application has three pods:
Pod
Labels
Role
postgresql
tier=database
The database, behind the Service pgsql (port 5432)
webserver
tier=webserver
The only client allowed to reach the database
external
app=external
Any other pod: must reach nothing
The lab works on a cluster shared by the trainees: each one works in a namespace of their own. The NetworkPolicies are enforced by the CNI plugin: the training cluster runs Cilium, which supports them.
podSelector: {} selects all the pods of the namespace. A policy with policyTypes: [Ingress] and no ingress rule allows nothing: the selected pods are isolated in ingress. The egress is still open.
Exercise 2: allow the webserver to reach the database
Create a NetworkPolicy db-from-webserver which allows the pods tier=webserver to connect to the pods tier=database on port 5432 only.
The NetworkPolicies are additive: a connection is allowed if one policy allows it. default-deny-ingress does not block what db-from-webserver allows.
Exercise 3: deny all the egress traffic, except DNS
Create a NetworkPolicy default-deny-egress which denies all the outgoing connections of all the pods of the namespace. Test the connections: why is webserver -> pgsql blocked now?
Allow the DNS requests of all the pods to the DNS server of the cluster (pods k8s-app=kube-dns in kube-system, port 53 in UDP and TCP).
Allow the egress traffic from the webserver to the database, on port 5432.
Rule A, one element with two selectors: the pods tier=webserverof the namespaces team=frontend (AND).
Rule B, two elements (two -): all the pods of the namespaces team=frontend, or the pods tier=webserver of the namespace of the policy (OR).
One dash changes the meaning: it is a classic trap of the exam. The rule allow-dns of exercise 3 uses the AND form, to only allow the CoreDNS pods of kube-system.
Questions
A pod is selected by no NetworkPolicy. Which traffic is allowed?
Do the NetworkPolicies filter the traffic of the pods with hostNetwork: true?
Answers
Everything: a pod is isolated, in ingress or egress, only if a policy with this policyType selects it.
No: they share the network of the node, the CNI plugin does not see their traffic as pod traffic. It is one more reason to forbid hostNetwork (Pod Security Standards baseline).