NetworkPolicies

Kubernetes · lesson 22 of 32 · 4 min read

Close the flat cluster network so only the pods that should talk to each other can.

Open this lesson in the learning hub

Key points

  • By default every pod can reach every other pod in the cluster. A NetworkPolicy is the only way to stop that.
  • The moment one policy selects a pod, that direction becomes deny-by-default for it. Pods no policy selects stay wide open.
  • ingress and egress are independent. Allowing traffic in says nothing about what that pod may call out to.
  • Your CNI has to enforce them. Calico and Cilium do; on some clusters policies are accepted and quietly ignored, so test yours.
  • Blocked packets are dropped rather than refused, so the symptom is a connection timeout, not a clear error.
  • Do not forget DNS. An egress policy with no rule for UDP 53 to kube-dns breaks every hostname lookup in the pod.

Example

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-allow-orders
  namespace: prod
spec:
  podSelector:
    matchLabels:
      app: db                    # selecting it flips db to deny-by-default
  policyTypes: ["Ingress"]
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: orders        # only this app, nothing else
      ports:
        - protocol: TCP
          port: 5432
---
# egress must still allow DNS or every lookup fails
  policyTypes: ["Egress"]
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
      ports:
        - protocol: UDP
          port: 53

One policy flips a pod from open to closed. Verify it, because a passive CNI ignores it.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Kubernetes course, and every lesson in it is listed on the Kubernetes contents page.