DevOps Dictionary

Kubernetes NetworkPolicy

Kubernetes NetworkPolicy is a Kubernetes resource that controls network traffic to and from pods. It lets you define which pods, namespaces, or IP ranges can communicate with selected pods, usually to reduce unwanted lateral movement inside a cluster.

What Kubernetes NetworkPolicy does

By default, Kubernetes allows pods to talk to each other inside the cluster, unless your network plugin or platform adds stricter rules. A NetworkPolicy changes that behavior for the pods it selects.

You can use NetworkPolicy to control:

  • Ingress traffic: which sources can connect to a pod.
  • Egress traffic: which destinations a pod can connect to.
  • Pod-to-pod communication: based on Kubernetes labels.
  • Namespace-to-namespace communication: based on namespace labels.
  • External IP access: using IP blocks, with some caveats around NAT and cloud networking.

How it works

A NetworkPolicy is a namespaced Kubernetes object. It selects pods with a podSelector, then defines allowed ingress and/or egress rules for those pods.

NetworkPolicies are allowlists. Standard Kubernetes NetworkPolicy does not define explicit deny rules. If traffic is not allowed by a policy that applies to the pod, Kubernetes should block it, assuming the cluster network plugin supports NetworkPolicy enforcement.

The main rule to remember is this:

  • If no NetworkPolicy selects a pod, traffic is allowed by default.
  • If at least one ingress policy selects a pod, only allowed ingress traffic can reach it.
  • If at least one egress policy selects a pod, only allowed egress traffic can leave it.
  • Multiple policies are additive. If any policy allows the traffic, it is allowed.

NetworkPolicy example

This example allows only pods with the label app: api in the same namespace to connect to pods labeled app: database on TCP port 5432:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-api-to-database
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: database
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: api
      ports:
        - protocol: TCP
          port: 5432

With this policy in place, other pods in the production namespace cannot connect to the database pods unless another NetworkPolicy allows that traffic.

Common use cases

  • Isolate databases: allow only backend services to connect to PostgreSQL, MySQL, Redis, or MongoDB pods.
  • Separate environments: prevent workloads in dev or staging namespaces from reaching production pods.
  • Limit outbound access: restrict pods so they can only call approved services, APIs, or CIDR ranges.
  • Protect multi-tenant clusters: reduce accidental traffic between teams, products, or customer workloads.
  • Support compliance controls: document and enforce which services can communicate inside the cluster.

Key parts of a NetworkPolicy

  • podSelector: selects the pods the policy applies to. An empty selector selects all pods in the namespace.
  • policyTypes: defines whether the policy controls Ingress, Egress, or both.
  • ingress: lists allowed inbound traffic sources and ports.
  • egress: lists allowed outbound traffic destinations and ports.
  • namespaceSelector: allows traffic based on namespace labels.
  • podSelector inside rules: allows traffic based on pod labels.
  • ipBlock: allows traffic to or from CIDR ranges, often used for external services.
  • ports: limits traffic by protocol and port, such as TCP 443 or UDP 53.

Network plugin requirements

Kubernetes defines the NetworkPolicy API, but enforcement depends on the cluster’s Container Network Interface, or CNI, plugin. Common CNI plugins with NetworkPolicy support include Calico, Cilium, Antrea, and Weave Net.

If your CNI does not support NetworkPolicy, Kubernetes may accept the resource, but traffic will not be restricted. This is a common source of false confidence, especially in clusters created quickly for early-stage products or internal platforms.

When you manage cluster resources as code, keep NetworkPolicy manifests in the same review path as Deployments, Services, and Ingress objects. For example, teams using Terraform for Kubernetes objects can manage these policies alongside other manifests, as shown in this guide to deploy Kubernetes resources using Terraform.

Benefits

  • Reduced blast radius: a compromised pod has fewer reachable targets.
  • Clear service boundaries: teams can define which workloads should communicate.
  • Better production hygiene: accidental connections between services become easier to catch.
  • Policy as code: rules can be reviewed, versioned, tested, and deployed through CI/CD.
  • Useful baseline security: NetworkPolicy gives you practical network segmentation without changing application code.

Limitations and tradeoffs

  • No standard deny rule: Kubernetes NetworkPolicy uses additive allow rules. Some CNIs add custom deny features, but those are provider-specific.
  • Layer 3 and Layer 4 only: standard NetworkPolicy works with IPs, ports, and protocols. It does not understand HTTP paths, JWT claims, or gRPC methods.
  • DNS needs explicit handling: if you restrict egress, pods may lose DNS resolution unless you allow traffic to CoreDNS, commonly UDP and TCP port 53.
  • Label accuracy matters: incorrect pod or namespace labels can allow too much traffic or block valid traffic.
  • CNI behavior varies: advanced features, logging, and policy debugging differ between Calico, Cilium, cloud CNIs, and managed Kubernetes platforms.

NetworkPolicy should be checked during cluster maintenance and upgrades because CNI changes can affect enforcement behavior. This is one reason Kubernetes upgrade planning should include networking validation, similar to the checks covered in these practical tips for Kubernetes upgrades for startups.

Simple real-world example

Say your production namespace runs three services:

  • frontend, which receives public traffic through an Ingress controller.
  • api, which handles business logic.
  • postgres, which stores application data.

A sensible policy setup might be:

  • Allow the Ingress controller to connect to frontend on port 8080.
  • Allow frontend to connect to api on port 8080.
  • Allow api to connect to postgres on port 5432.
  • Block direct traffic from frontend to postgres.
  • Allow DNS egress from all app pods to CoreDNS.

This setup matches the intended application flow and blocks common accidental paths. If a frontend pod is compromised, it cannot connect directly to the database unless another policy permits it.

How NetworkPolicy differs from related controls

NetworkPolicy vs Kubernetes Service

A Kubernetes Service gives pods a stable virtual address and load-balances traffic to matching pods. It does not decide whether that traffic should be allowed. NetworkPolicy controls whether selected traffic can pass.

NetworkPolicy vs Ingress

Ingress manages external HTTP or HTTPS routing into the cluster, usually through an Ingress controller such as NGINX, Traefik, or AWS Load Balancer Controller. NetworkPolicy controls pod network traffic inside the cluster and sometimes traffic from pods to external IP ranges.

NetworkPolicy vs cloud security groups

Cloud security groups usually apply to nodes, network interfaces, load balancers, or managed services. NetworkPolicy applies to Kubernetes pods. In managed Kubernetes environments, you often need both because they operate at different layers.

NetworkPolicy vs service mesh policies

Service mesh tools such as Istio and Linkerd can enforce application-aware policies, mTLS, and identity-based traffic rules. NetworkPolicy works at the network layer. Many teams use NetworkPolicy as a baseline and service mesh policies for service identity and request-level control.

Practical implementation tips

  • Start with visibility: map actual service traffic before applying restrictive policies in production.
  • Use namespaces consistently: label namespaces by environment, team, or tenant, such as environment=prod.
  • Apply default deny policies: create namespace-level default deny rules, then add explicit allow policies.
  • Allow DNS early: many apps fail in confusing ways when DNS egress is blocked.
  • Test with simple tools: use temporary pods with curl, nc, or dig to verify expected allow and block behavior.
  • Keep policies close to apps: store NetworkPolicy manifests with the service chart, Kustomize overlay, or deployment module.
  • Review policies during platform changes: CNI migrations, EKS upgrades, node OS changes, and cluster rebuilds can change enforcement details.

For teams building Kubernetes-first platforms, NetworkPolicy often sits next to other infrastructure-as-code workflows. If your platform provisions cloud resources through Kubernetes APIs, the same operating model can apply to tools such as Crossplane, including patterns used to deploy AWS resources using Crossplane on Kubernetes.

Bottom line

Kubernetes NetworkPolicy is the standard way to control pod-level network access in a cluster. It gives DevOps, platform, and security teams a practical way to define allowed traffic paths, reduce unnecessary access, and treat internal cluster networking as code. Its value depends on clear labels, careful testing, and a CNI plugin that enforces the policies correctly.

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
Y
X
Z