Task 6: Securing Network Traffic

Objective:
Create a NetworkPolicy that allows traffic to pods in the restricted namespace only when:

Step 1 - Create Namespaces

kubectl create namespace restricted

kubectl create namespace access

Verify:

kubectl get ns

Step 2 - Create the nginx Pod

Create the web server in the restricted namespace.

kubectl run lab156web \
--image=nginx \
--namespace=restricted \
--port=80

Verify:

kubectl get pods -n restricted

Step 3 - Create the Access Pod

Create a BusyBox pod in the access namespace with the required label.

kubectl run lab156access \
--image=busybox \
--namespace=access \
--labels=access=true \
--restart=Never \
-- sleep 3600

Verify labels:

kubectl get pods -n access --show-labels

Step 4 - Create the NetworkPolicy

Create the file restricted-policy.yaml.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-access-port-80
  namespace: restricted

spec:
  podSelector: {}

  policyTypes:
  - Ingress

  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: access

      podSelector:
        matchLabels:
          access: "true"

    ports:
    - protocol: TCP
      port: 80

Apply the policy:

kubectl apply -f restricted-policy.yaml

Step 5 - Verify the Policy

Check that the policy exists:

kubectl get netpol -n restricted

kubectl describe netpol allow-access-port-80 -n restricted

Expected output:

NamespaceSelector: kubernetes.io/metadata.name=access
PodSelector: access=true
Port: 80/TCP

Exam Shortcut (Fastest Method)

kubectl create ns restricted

kubectl create ns access

kubectl run lab156web \
--image=nginx \
-n restricted \
--port=80

kubectl run lab156access \
--image=busybox \
-n access \
--labels=access=true \
--restart=Never \
-- sleep 3600
CKA Exam Keywords