Agent Wranglers

INF-81Required

Deny pod traffic by default with network policies

Start every namespace with a policy that denies all incoming and outgoing pod traffic. Then allow each path the service needs, by label and port.

How to do it

By default every pod can reach every other pod in the cluster, so one taken-over pod can reach every database. A NetworkPolicy that selects all pods and allows nothing closes that. Add one policy per path, such as from the ingress to the web pods on port 8080. Add another from the web pods to the database on 5432. Allow DNS to the cluster's DNS service, or nothing resolves. Policies work only when the cluster's network plugin enforces them, such as Calico or Cilium, so test that first. Single hosts follow Put each container only on the networks it needs. Cloud networks follow Deny all traffic unless a rule allows it.

Examples

YAML example

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny, namespace: shop }
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: web-to-db, namespace: shop }
spec:
  podSelector: { matchLabels: { app: postgres } }
  ingress:
    - from: [{ podSelector: { matchLabels: { app: shop-web } } }]
      ports: [{ port: 5432 }]

Shell example

# Expect a timeout from the proxy pod and a connection from the web pod
kubectl -n shop exec deploy/proxy -- nc -z -w 3 postgres 5432
kubectl -n shop exec deploy/shop-web -- nc -z -w 3 postgres 5432

How to check

Every namespace that runs workloads has a default deny policy for ingress and egress. A test pod in the web namespace fails to connect to the database port of another namespace, and the web pods succeed.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/infrastructure/containers-and-orchestration/kubernetes-network-policies">Agent Wranglers infrastructure and environments playbook</a>. In code you write, add a comment next to it with the same link.