Challenge ·Easy

CKA Practice: Configure Network Policies To Restrict Traffic Between Pods

This exercise tests your ability to configure kubernetes network policies to make sure only pods with specific labels can communicate with each other.

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!

Diagram showing desired network policy configuration between frontend and backend pods

First, create a namespace called "app":

Now, create two deployments in that namespace.

  1. Frontend:
    • Deployment "frontend" with 2 replicas running ghcr.io/iximiuz/labs/nginx:alpine
    • Declares container port 80 and serves HTTP on it
  2. Backend:
    • Deployment "backend" with 2 replicas running ghcr.io/lpmi-13/default-go
    • Declares container port 8000 and serves HTTP on it

Now, label the pods:

  1. All frontend pods should have: role=frontend
  2. All backend pods should have: tier=api
  3. Only one backend pod should have the additional label: role=backend
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:

  1. All frontend pods can send traffic to any backend pod with label tier=api on port 8000
  2. Only the backend pod with label role=backend can send traffic to frontend pods with label role=frontend on port 80
  3. All other ingress traffic to the frontend and backend pods is denied
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
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend
    ports:
    - port: 8000
      protocol: TCP