Complete a NetworkPolicy so api Pods accept traffic only from role=frontend.
In namespace shop, the api Pods (label app=api) accept traffic from everyone because no policy selects them. Restrict ingress so ONLY Pods labelled role=frontend may reach them, and only on TCP port 8080. Complete the manifest.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow-frontend
namespace: shop
spec:
podSelector:
matchLabels:
app: api
# TODO: allow ingress only from role=frontend on TCP 8080
Add the missing policyTypes and ingress rule.
Set policyTypes to Ingress and one ingress rule whose from is a podSelector on role=frontend, limited to TCP port 8080. Selecting the api Pods flips them to deny-by-default for ingress, so only that rule passes. It works only if the CNI enforces NetworkPolicy.
- ✗Restricting the sender with egress instead of selecting the api Pods
- ✗Forgetting the ports block, which leaves all ports open
- ✗Assuming the policy works without a CNI (Container Network Interface) that enforces NetworkPolicy
- →How would you also allow ingress from a monitoring namespace by label?
- →What happens to existing connections the moment this policy is applied?
Solution
The api Pods are open to everyone because no NetworkPolicy selects them — the namespace is allow-all by default. The moment a policy selects those Pods via its podSelector, they flip to deny-by-default for the chosen directions, and only what is explicitly allowed passes.
You need policyTypes set to Ingress; one ingress rule whose from is a podSelector on role=frontend; and a ports entry for TCP 8080. Everything else (other sources, other ports) is dropped.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow-frontend
namespace: shop
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 8080
Note: a NetworkPolicy is enforced by the CNI (Container Network Interface) plugin. On a CNI without policy support (e.g. plain flannel) the manifest is accepted but the rule has no effect.