NetworkPolicy in Kubernetes: Secure Your Cluster Network
By default, all pods in Kubernetes can communicate with each other. While this is convenient for development, it’s a security risk in production. NetworkPolicies let you control traffic flow between pods—essentially acting as a firewall within your cluster.
Prerequisites
NetworkPolicies require a CNI that supports them:
- Calico ✅
- Cilium ✅
- Weave Net ✅
- Flannel ❌ (does not support NetworkPolicy)
NetworkPolicy Anatomy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: my-policy
namespace: default
spec:
podSelector: # Which pods this policy applies to
matchLabels:
app: web
policyTypes: # Ingress, Egress, or both
- Ingress
- Egress
ingress: # Allowed incoming traffic
- from:
- podSelector:
matchLabels:
app: frontend
egress: # Allowed outgoing traffic
- to:
- podSelector:
matchLabels:
app: databaseCommon NetworkPolicy Patterns
1. Deny All Ingress Traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
namespace: production
spec:
podSelector: {} # Apply to all pods
policyTypes:
- Ingress2. Deny All Egress Traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-egress
namespace: production
spec:
podSelector: {}
policyTypes:
- Egress3. Allow Traffic from Specific Pods
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend
spec:
podSelector:
matchLabels:
app: api
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 80804. Allow Traffic from Specific Namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-monitoring
namespace: production
spec:
podSelector:
matchLabels:
app: web
ingress:
- from:
- namespaceSelector:
matchLabels:
name: monitoring5. Allow DNS Egress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- namespaceSelector: {}
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53Testing NetworkPolicies
# Create a test pod
kubectl run test --image=busybox --rm -it -- /bin/sh
# Test connectivity
wget -qO- --timeout=2 http://web-serviceExam Tips
NetworkPolicies appear frequently in CKA and CKS exams:
- Know the difference between
podSelectorandnamespaceSelector - Understand that empty
podSelector: {}means “all pods” - Remember: If no policies exist, all traffic is allowed
- If any policy exists, only explicitly allowed traffic is permitted
Practice NetworkPolicy Scenarios
NetworkPolicies are best understood through hands-on practice. At Sailor.sh, we provide real clusters with Calico pre-installed where you can:
- Create and test NetworkPolicies
- Debug connectivity issues
- Practice exam scenarios
Start practicing: Sailor.sh