CKAD — Network Policies

1 minute read

Network Policies

By default, all Pods can communicate with all other Pods. Network Policies restrict this by defining allowed ingress (incoming) and egress (outgoing) traffic.

How Network Policies Work

  • Network Policies are additive — if any policy allows the traffic, it is allowed
  • Pods with no Network Policy: all traffic allowed (default)
  • Pods with any Network Policy: only explicitly allowed traffic is permitted (default deny for the policy type)
  • Network Policies require a CNI plugin that supports them (Calico, Cilium, Weave Net — NOT Flannel)

Default Deny All Ingress

Block all incoming traffic to Pods in a namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-ingress
  namespace: default
spec:
  podSelector: {}    # Selects ALL Pods in the namespace
  policyTypes:
  - Ingress
  # No ingress rules = deny all incoming traffic

Default Deny All Egress

Block all outgoing traffic from Pods in a namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-egress
  namespace: default
spec:
  podSelector: {}
  policyTypes:
  - Egress

Allow Specific Ingress

Allow traffic to app=web Pods only from app=api Pods on port 80:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-api-to-web
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: api
    ports:
    - protocol: TCP
      port: 80

Allow Specific Egress

Allow app=api Pods to connect to app=db Pods on port 5432 and DNS (port 53):

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-egress
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: db
    ports:
    - protocol: TCP
      port: 5432
  - to: []                    # Allow DNS
    ports:
    - protocol: UDP
      port: 53
    - protocol: TCP
      port: 53

Important: If you restrict egress, always allow DNS (port 53 UDP/TCP) or Pod DNS resolution will break.


Next: Network Policy Selectors →

Updated: