CKAD field manual

k8s NetworkPolicy YAML example

A NetworkPolicy is deny-by-default for the pods it selects, for the policyTypes you list.

A gold mask stays on the column while people cycle through the door behind it. A gold mask stays on the column while people cycle through the door behind it.
Deny all ingress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-ingress
  namespace: app
spec:
  podSelector: {}
  policyTypes:
    - Ingress
Allow from a Pod
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend
  namespace: app
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080
Allow DNS
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: app
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53

Fields

podSelector
{} = every Pod in this namespace. This is who the policy applies to.
policyTypes
Only list what you mean. Egress here + only DNS = all other egress is denied.
from
Peers are OR. podSelector + namespaceSelector on the same peer are AND.
ingress
Missing ingress: + policyTypes Ingress = deny all inbound to the selected Pods.

Watch

  • podSelector: {} = every Pod in this namespace. An empty ingress: [] denies all ingress.
  • Peers in from: are OR. podSelector and namespaceSelector on the same peer are AND.
  • Listing Egress and only allowing DNS denies every other egress. Add policyTypes only for what you mean.

Official docs Network Policies

Practice these objects on a live cluster →