A NetworkPolicy ingress rule lets you allow traffic only from specific Pods (e.g., βonly frontend can talk to backendβ).
β This is the most common use case for NetworkPolicy in microservices apps.
Like a VIP list at a club:
- Only guests with a green wristband (
app: frontend) can enter the VIP room (app: backend)
frontend to Access backendAssume you already have:
frontend Deployment (label: app: frontend)backend Deployment (label: app: backend)Step 1: Apply a NetworkPolicy to Allow Only frontend
# allow-frontend-to-backend.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
name: allow-frontend-to-backend
namespace: default
spec:
podSelector:
matchLabels:
app: backend # β Policy applies to backend Pods
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend # β Only Pods with this label can connect
ports:
- protocol: TCP
port: 80
Apply it:
kubectl apply -f allow-frontend-to-backend.yaml
Step 2: Test Access
β From frontend β backend (should work):
kubectl exec deploy/frontend -- curl -m 3 <http://backend>
# β
Returns HTTP response
β From any other Pod β backend (should fail):
# Create a test Pod (not labeled as frontend)
kubectl run tester --image=busybox --rm -it -- sh
/ # wget -qO- <http://backend>
# β Hangs or times out