Configuring Network Policies
1. Creating NetworkPolicy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: allow-web, namespace: prod }
spec:
podSelector: { matchLabels: { app: web } }
policyTypes: [Ingress, Egress]
ingress:
- from:
- podSelector: { matchLabels: { app: gateway } }
ports:
- { protocol: TCP, port: 8080 }
egress:
- to:
- podSelector: { matchLabels: { app: db } }
ports: [{ protocol: TCP, port: 5432 }]
Note: Requires CNI plugin support (Calico, Cilium, Antrea). Default flat networking has no enforcement.
2. Defining Pod Selectors
| Selector | Effect |
podSelector: {} | All pods in namespace |
matchLabels: {app: web} | Specific pods |
3. Configuring Ingress Rules
| Source Type | Field |
| Pods | podSelector |
| Namespaces | namespaceSelector |
| IPs | ipBlock |
4. Configuring Egress Rules
egress:
- to:
- ipBlock: { cidr: 10.0.0.0/8, except: [10.0.5.0/24] }
ports: [{ protocol: TCP, port: 443 }]
5. Using Namespace Selectors
ingress:
- from:
- namespaceSelector: { matchLabels: { env: prod } }
podSelector: { matchLabels: { app: gateway } }
| Combination | Logic |
ns + pod in same - | AND |
Separate - entries | OR |
6. Allowing Specific Ports
ports:
- { protocol: TCP, port: 8080 }
- { protocol: TCP, port: http } # named port
- { protocol: TCP, port: 8000, endPort: 9000 } # range
7. Using IP Blocks
from:
- ipBlock:
cidr: 0.0.0.0/0
except: [10.0.0.0/8, 192.168.0.0/16]
8. Implementing Default Deny All
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny, namespace: prod }
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
Warning: Default-deny breaks DNS. Always pair with allow-egress to kube-system/kube-dns on UDP/TCP 53.
9. Testing Network Policies
kubectl run test --rm -it --image=nicolaka/netshoot -- bash
# inside: nc -zv web 8080
kubectl exec POD -- curl -m 3 service:port
10. Listing Network Policies
kubectl get networkpolicy -A
kubectl describe netpol allow-web -n prod