Network Policies Overview
By default, all Kubernetes pods can communicate with any other pod in the cluster. Network Policies enable you to define rules that restrict traffic between pods, implementing the principle of least privilege at the network level. This is critical for multi-tenant and security-conscious environments.
💡 Key Insight: Without network policies, a compromised pod can access all other pods
and services in the cluster. Network segmentation is a critical security control.
Network Policy Concepts
Pod Selectors
Identify which pods the policy applies to:
podSelector:
matchLabels:
tier: backend
Ingress Rules
Control incoming traffic to pods:
- From specific pods (pod selectors)
- From specific namespaces
- On specific ports and protocols
Egress Rules
Control outgoing traffic from pods:
- To specific pods
- To external IPs
- On specific ports and protocols
Network Policy Examples
1. Default Deny All Incoming Traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
spec:
podSelector: {}
policyTypes:
- Ingress
2. Allow Specific Pod Communication
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
spec:
podSelector:
matchLabels:
tier: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
tier: frontend
ports:
- protocol: TCP
port: 8080
3. Allow Egress to DNS
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-egress
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
Network Policy Implementations
CNI Implementations
| CNI Plugin | Network Policy Support |
|---|---|
| Calico | Full support, advanced policies |
| Cilium | Full support, eBPF-based, advanced features |
| Flannel | Basic support (with additional tools) |
| Weave | Full support |
Service Mesh Approach
For advanced traffic management, use service mesh:
- Istio: VirtualService and DestinationRule for fine-grained control
- Linkerd: Lightweight, built-in security
- Consul: Multi-cluster networking
Best Practices
- Start with Deny All: Create a default deny policy, then allow specific traffic
- Label Everything: Use consistent labels for pod selection
- Document Policies: Maintain clear documentation of traffic flows
- Test Thoroughly: Test policies in staging before production
- Monitor Traffic: Use tools like Cilium to visualize and monitor traffic
- Regular Audits: Review policies regularly to remove unused rules
⚠️ Important: Not all CNI plugins support network policies. Verify your CNI implementation
before relying on network policies for security.