In this exercise, you will configure network policies to control traffic flow between two deployments in a Kubernetes cluster. You'll need to ensure specific pods can communicate based on their labels while blocking unauthorized traffic. Have fun!
First, create a namespace called "app":
Hint 1 💡
Check the documentation for creating namespaces
Now, create two deployments in that namespace.
- Frontend:
- Deployment "frontend" with 2 replicas running
ghcr.io/iximiuz/labs/nginx:alpine
- Accessible on port 80
- Deployment "frontend" with 2 replicas running
- Backend:
- Deployment "backend" with 2 replicas running
ghcr.io/lpmi-13/default-go
- Accessible on port 8000
- Deployment "backend" with 2 replicas running
Hint 2 💡
Check the documentation for creating deployments
Now, label the pods:
- All frontend pods should have:
role=frontend
- All backend pods should have:
tier=api
- Only one backend pod should have the additional label:
role=backend
Hint 3 💡
Check the documentation for adding labels
Hint 4 💡
# Get the name of one backend pod
BACKEND_POD=$(kubectl get pods -n app -l app=backend -o jsonpath='{.items[0].metadata.name}')
Finally, create network policies to make sure:
- All frontend pods can send traffic to any backend pod with label
tier=api
on port 8000 - Only the backend pod with label
role=backend
can send traffic to frontend pods with labelrole=frontend
on port 80 - All other traffic should be denied by default
Hint 5 💡
Create two network policies, one for the frontend => backend, and another from the backend => frontend. Here's the first one:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: frontend-to-backend
namespace: app
spec:
podSelector:
matchLabels:
tier: api
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- port: 8000
protocol: TCP
Level up your Server Side game — Join 9,000 engineers who receive insightful learning materials straight to their inbox