Out of the box Kubernetes networking is flat and open. A NetworkPolicy restricts it, but only if your network plugin enforces it (Calico and Cilium do; some simple plugins do not).
Start with a default deny in the namespace:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny, namespace: shop }
spec:
podSelector: {}
policyTypes: [Ingress]
Then allow only what is needed:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: db-from-api, namespace: shop }
spec:
podSelector:
matchLabels: { app: db }
ingress:
- from:
- podSelector:
matchLabels: { app: api }
ports: [{ port: 5432 }]
Remember DNS and monitoring when you also restrict egress. Test with a temporary pod: kubectl run t --rm -it --image=busybox:1.33 -- nc -zv db 5432.