Egress Policy — control outbound traffic from Pods.
1apiVersion: networking.k8s.io/v12kind: NetworkPolicy3metadata:4 name: allow-egress5 namespace: production6spec:7 podSelector:8 matchLabels:9 app: myapp10 policyTypes:11 - Egress12 egress:13 # Allow DNS14 - to:15 - namespaceSelector: {}16 ports:17 - protocol: UDP18 port: 5319 - protocol: TCP20 port: 5321 # Allow PostgreSQL in same namespace22 - to:23 - podSelector:24 matchLabels:25 app: postgres26 ports:27 - protocol: TCP28 port: 543229 # Allow external API30 - to:31 - ipBlock:32 cidr: 104.16.0.0/12 # Cloudflare33 ports:34 - protocol: TCP35 port: 44336 # Block all other egress37 # (implicit deny-all when policyTypes includes Egress)
1# Commands2kubectl get networkpolicy -n production3kubectl describe networkpolicy allow-egress -n production45# Test egress6kubectl exec -it my-pod -- wget -qO- https://api.example.com # Should work7kubectl exec -it my-pod -- curl http://random-site.com # Should fail8kubectl exec -it my-pod -- nslookup postgres # Should work910# Check NetworkPolicy status11kubectl get networkpolicy -n production -o wide12kubectl describe networkpolicy -n production
Egress Rules:
Best Practices: