tezvyn:

Kubernetes NetworkPolicy: A Firewall for Pods

AI-drafted, machine-checkedSource: kubernetes.ioadvanced
Kubernetes NetworkPolicy: A Firewall for Pods

NetworkPolicy is a firewall for pods, locking down traffic in a cluster where everything can talk to everything by default. Use it to isolate services, like preventing a web frontend from directly accessing a database.

WHY IT EXISTS: By default, a Kubernetes cluster has a flat network where any pod can communicate with any other pod, regardless of namespace. This simplicity is a security risk, violating the principle of least privilege. NetworkPolicy was created to provide a native way to control and segment this traffic.

THE MENTAL MODEL: Think of NetworkPolicy as the rulebook for a bouncer standing at the door of your pods. It doesn't act as the bouncer itself; instead, it tells a compatible network plugin (like Calico or Cilium) who's on the guest list. You declare rules like "only pods with the label 'app=frontend' can talk to pods with 'app=backend' on port 8080."

HOW IT WORKS: A NetworkPolicy is a Kubernetes resource defined in YAML. It has three key components. First, a podSelector targets the group of pods the policy will apply to. Second, ingress rules define what incoming traffic is allowed. Third, egress rules define what outgoing traffic is allowed. If a pod is selected by any policy, it enters a "deny-by-default" mode. Any traffic not explicitly allowed by a rule is dropped. If no policy selects a pod, all traffic is allowed.

WHEN TO USE IT: Use NetworkPolicy to enforce security boundaries in production. A classic use case is isolating a database so only the backend application pods can connect to it. It's also essential for multi-tenancy, preventing one customer's application from accessing another's. It's a key tool for achieving compliance standards like PCI-DSS or HIPAA within a cluster.

WHEN NOT TO USE IT: NetworkPolicy objects have no effect if your cluster's network plugin doesn't support them. Many basic CNI plugins do not enforce these policies, so you must verify you have a compatible plugin installed. For very simple, single-application clusters where all components are trusted, they might be considered overkill, but this is rare in production.

ONE CANONICAL EXAMPLE: A common starting point is to implement a default-deny policy for an entire namespace. You create a NetworkPolicy that selects all pods in the namespace (using an empty podSelector: {}) but specifies no ingress rules. This immediately blocks all incoming traffic to all pods. From there, you add more specific policies to incrementally open up required pathways, such as allowing ingress from the Kubernetes Ingress Controller or allowing egress for DNS lookups. This forces a secure, "allow-list" approach to network security.

Read the original → kubernetes.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.