A NetworkPolicy is a Kubernetes resource that controls traffic flow between Pods β like a firewall for your cluster.
β By default, all Pods can talk to each other (open network).
π NetworkPolicy adds restrictions β βonly allow X to talk to Yβ.
Like a building security system:
- Without policy: Anyone can walk into any office
- With policy: Only HR can enter payroll room; devs can only access dev servers
Step 1: Deploy two apps (no policy yet)
# frontend.yaml
apiVersion: apps/v1
kind: Deployment
meta
name: frontend
labels:
app: frontend
spec:
selector:
matchLabels:
app: frontend
template:
meta
labels:
app: frontend
spec:
containers:
- name: nginx
image: nginx
---
apiVersion: v1
kind: Service
meta
name: frontend
spec:
selector:
app: frontend
ports:
- port: 80
# backend.yaml
apiVersion: apps/v1
kind: Deployment
meta
name: backend
labels:
app: backend
spec:
selector:
matchLabels:
app: backend
template:
meta
labels:
app: backend
spec:
containers:
- name: httpd
image: httpd
Apply:
kubectl apply -f frontend.yaml -f backend.yaml
β
Right now: frontend can curl <http://backend> β allowed
# deny-all-backend.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
name: deny-all-to-backend
namespace: default
spec:
podSelector:
matchLabels:
app: backend # β Applies to Pods with this label
policyTypes:
- Ingress # β Control incoming traffic
ingress: [] # β Empty = deny ALL
Apply:
kubectl apply -f deny-all-backend.yaml
Now test:
# From frontend Pod
kubectl exec deploy/frontend -- curl -m 3 <http://backend>
# β Connection timed out!