NetworkPolicies

Kubernetes · Advanced · 10 min

By default every pod can reach every other pod; one compromised pod can then reach your database.

Without policies the pod network is flat: any pod can connect to any other in any namespace. A NetworkPolicy selects pods with podSelector and lists what traffic is allowed for them.

Semantics to get right:

  • Once any policy selects a pod for Ingress (or Egress), that direction becomes deny by default for it, and only listed traffic is allowed. Policies are additive allow-lists.
  • Sources/destinations: podSelector (same namespace), namespaceSelector (whole namespaces, e.g. kubernetes.io/metadata.name: monitoring), both in one entry (pods with label X in namespaces Y), or ipBlock.
  • ports narrow by protocol and port.
  • Replies to allowed connections are allowed automatically.

A common baseline per namespace: a default-deny policy (podSelector: {} with policyTypes: [Ingress, Egress]), then explicit allows. With egress deny, remember to allow DNS (UDP and TCP 53 to kube-dns) or nothing resolves.

Enforcement is done by the CNI plugin. Calico, Cilium and most managed offerings enforce policies; some simple CNIs (like kind's default) don't, and then policies are silently ignored.

Standard NetworkPolicy works at L3/L4. For HTTP-level rules or mTLS identities, look at Cilium policies or a service mesh.

Example

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny, namespace: shop}
spec:
  podSelector: {}
  policyTypes: [Ingress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: db-from-api, namespace: shop}
spec:
  podSelector: {matchLabels: {app: db}}
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector: {matchLabels: {app: api}}
      ports:
        - {protocol: TCP, port: 5432}
# from an api pod: nc -zv db 5432  -> open
# from a web pod:  nc -zv db 5432  -> times out

Remember

  • Pods selected by any policy become default-deny for that direction
  • Policies only add allowed traffic
  • The CNI must support NetworkPolicy; with egress deny, allow DNS

Watch out for

  • Applying an egress default-deny and breaking all DNS lookups.

Check yourself

  1. Two policies select the db pods: one allows from app=api, one allows from app=worker. Which pods can connect?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kubernetes.io/docs/concepts/services-networking/network-policies/