Control pod-to-pod traffic with network policies
In this task you'll allow only the traffic between pods that the design needs.
By default any pod can reach any other. A NetworkPolicy selects pods and lists who may connect to them and on which ports. Start with a default deny for the namespace, then add allow rules.
The cluster needs a policy engine: on AKS, Azure Network Policy Manager, Calico or Cilium (chosen when the cluster is created).
Example. In Ironbridge Payments' cluster only the api pods can reach the database pods on 5432; a compromised web pod can't.
Costs money. This task creates resources that are charged while they exist. Delete them as soon as you finish.
Before you start
You need: An AKS cluster with a network policy engine. Time: 25 minutes.
Where to look
- NetworkPolicy YAML
- kubectl get networkpolicy
Steps
- Apply a default-deny policy (podSelector {}, policyTypes Ingress, no rules).
- Add one policy per allowed path, such as app=db from app=api on TCP 5432.
- Test from inside pods, for example
kubectl exec deploy/web -- /agnhost connect db:5432 --timeout=3swith the agnhost test image.
Commands
# Connect kubectl to the cluster first
az aks get-credentials -g <group> -n <cluster>
kubectl apply -n shop -f policies.yaml
kubectl get networkpolicy -n shop
kubectl get pods -n shop --show-labels
Watch out for
- Cost
- Free.
- Security
- Policies only work if the cluster has an engine; without one they're silently ignored.
- Common mistakes
- Labels in the policy that don't match the pods, and forgetting DNS if you also restrict egress.
Clean up
kubectl delete networkpolicy --all -n <ns>.
Words to know
- Default deny
- A policy that selects every pod and allows nothing in.
- podSelector
- Which pods a policy applies to, or which pods may connect.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On