Tutorials · DevSecOps & Cloud

How to Isolate Kubernetes Workloads With Network Policies

By default every pod in a Kubernetes cluster can talk to every other pod. Network policies are the cluster's firewall: deny by default, then allow only the flows each application needs.

Advanced15 min5 steps

Before you start

  • A Kubernetes cluster with a CNI that enforces NetworkPolicy (Calico, Cilium and others)
  • kubectl access to a namespace

Step by step

  1. Deny all traffic by default

    Apply a default-deny policy in each application namespace.

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: default-deny
      namespace: shop
    spec:
      podSelector: {}
      policyTypes: [Ingress, Egress]
    
  2. Allow DNS

    Pods need DNS to find services; allow egress to kube-dns.

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata: { name: allow-dns, namespace: shop }
    spec:
      podSelector: {}
      policyTypes: [Egress]
      egress:
      - to:
        - namespaceSelector: {}
          podSelector: { matchLabels: { k8s-app: kube-dns } }
        ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }]
    
  3. Allow the application flow

    Let only the web pods reach the API pods on the API port.

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata: { name: web-to-api, namespace: shop }
    spec:
      podSelector: { matchLabels: { app: api } }
      ingress:
      - from:
        - podSelector: { matchLabels: { app: web } }
        ports: [{ protocol: TCP, port: 8080 }]
    
  4. Apply and test

    Apply the files and test from a temporary pod that allowed traffic works and everything else times out.

    kubectl apply -f policies/
    kubectl -n shop run t --rm -it --image=busybox -- wget -qO- -T 3 http://api:8080/health
    
  5. Control egress to the outside

    Allow outbound traffic only to the services the app needs (database, payment API); block the rest to stop data exfiltration.

Commands are generic, industry-standard examples. Exact syntax and menu names vary by model and firmware; check your device's manual on the Documentation page.

Pro tips

  • Label pods consistently (app, tier) so policies stay readable.
  • Keep policies in Git next to the application manifests.