An egress rule in a NetworkPolicy lets you restrict which external destinations a Pod can talk to β for example, βbackend can only call the database, not the internet.β
β This is critical for security compliance and preventing data exfiltration.
Like a corporate firewall:
- Dev laptops can access internal Git, CI/CD, and package repos
- But not social media or random websites
Assume you have:
backend Deployment (app: backend)database Deployment (app: database)Step 1: Apply a NetworkPolicy to Restrict Egress from Backend
# restrict-backend-egress.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
meta
name: backend-egress-policy
namespace: default
spec:
podSelector:
matchLabels:
app: backend # β Policy applies to backend Pods
policyTypes:
- Egress # β Control outgoing traffic
egress:
- to:
- podSelector:
matchLabels:
app: database # β Only allow traffic to database Pods
ports:
- protocol: TCP
port: 5432 # β PostgreSQL port
Apply it:
kubectl apply -f restrict-backend-egress.yaml
Step 2: Test Outgoing Traffic
β From backend β database (should work):
kubectl exec deploy/backend -- nc -zv database 5432
# β
Succeeded
β From backend β internet (should fail):
kubectl exec deploy/backend -- wget -qO- <http://example.com> --timeout=3
# β Connection timed out