Restricting Pod ingress with a NetworkPolicy
NetworkPolicy ingress control.
Create a NetworkPolicy with podSelector app=frontend, policyTypes Ingress, and one ingress from-rule matching podSelector role=api-gateway; requires a CNI that enforces policies.
WHAT THIS TESTS Knowing the native primitive for Pod-level firewalling and its important default-deny semantics, plus the CNI dependency.
A GOOD ANSWER COVERS The native resource is NetworkPolicy. You create a policy whose spec.podSelector matches app=frontend, set policyTypes to include Ingress, and add a single ingress entry whose from list contains a podSelector matching role=api-gateway. The crucial behavior: as soon as a Pod is selected by any NetworkPolicy that includes Ingress, that Pod becomes default-deny for ingress, meaning all inbound traffic is blocked except what the policy explicitly allows. So this one policy both isolates the frontend and whitelists only the api-gateway Pods. If you need to scope by namespace too, add a namespaceSelector, since podSelector alone matches Pods in the policy's own namespace.
COMMON WRONG ANSWERS Forgetting that selecting a Pod turns it default-deny, and worrying you must also write an explicit deny rule. Assuming policies are enforced by Kubernetes itself; enforcement is done by the CNI, and plugins like Calico or Cilium are required. Mixing up podSelector (the targets) with the from selector (the allowed sources).
LIKELY FOLLOW-UPS How to also allow a whole namespace? Add namespaceSelector. What about egress? Add an Egress policyType. What if no CNI supports policy? The policy is silently ignored. Default-deny everything? An empty podSelector with no rules.
ONE CONCRETE EXAMPLE A NetworkPolicy in the tenant namespace selects app=frontend, policyTypes Ingress, with one ingress from podSelector role=api-gateway. After applying it on a Calico-backed cluster, a curl from an api-gateway Pod to a frontend Pod succeeds, while a curl from any other Pod times out, since the frontend is now default-deny except for the gateway.
Read the original → kubernetes.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.