CKAD — Network Policy Selectors

1 minute read

Namespace Selectors

Allow traffic from Pods in a specific namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-from-monitoring
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          team: monitoring

Combined Selectors (AND vs OR)

This is a common exam trap. The placement of - matters:

AND Logic — Pod Must Match BOTH Selectors

ingress:
- from:
  - namespaceSelector:
      matchLabels:
        team: frontend
    podSelector:          # Same array element = AND
      matchLabels:
        app: web

This means: allow from Pods labeled app=web AND in namespaces labeled team=frontend.

OR Logic — Pod Matches EITHER Selector

ingress:
- from:
  - namespaceSelector:
      matchLabels:
        team: frontend
  - podSelector:          # Separate array element = OR
      matchLabels:
        app: web

This means: allow from any Pod in namespaces labeled team=frontend OR any Pod labeled app=web in the current namespace.

Exam tip: AND vs OR in Network Policies is one of the most commonly tested topics. Look at the YAML indentation carefully — same list item = AND, separate list items = OR.

IP Block Selectors

Allow traffic from specific IP ranges:

ingress:
- from:
  - ipBlock:
      cidr: 10.0.0.0/8
      except:
      - 10.0.1.0/24

Network Policy Quick Reference

# List Network Policies
kubectl get networkpolicy
kubectl get netpol              # Short name

# Describe
kubectl describe netpol allow-api-to-web

# Delete
kubectl delete netpol allow-api-to-web

Next: Hands-On Lab →

Updated: