What Is Network Policy in Kubernetes: Simple Explanation and Example
NetworkPolicy in Kubernetes is a set of rules that controls how pods communicate with each other and with other network endpoints. It acts like a firewall inside the cluster, allowing you to restrict or allow traffic based on pod labels and ports.How It Works
Think of a Kubernetes cluster as a neighborhood where each pod is a house. By default, all houses can visit each other freely. A NetworkPolicy is like setting up fences and gates that decide who can visit whom.
When you create a NetworkPolicy, you define rules that specify which pods can send or receive traffic from other pods or IP addresses. These rules use labels to identify pods and specify allowed ports and protocols. If no policy applies, pods can communicate without restrictions.
This helps improve security by limiting access only to trusted pods, reducing the risk of unwanted or harmful traffic inside your cluster.
Example
This example shows a NetworkPolicy that allows incoming traffic only from pods with the label role=frontend to pods labeled role=backend on port 80.
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-frontend-to-backend namespace: default spec: podSelector: matchLabels: role: backend policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: role: frontend ports: - protocol: TCP port: 80
When to Use
Use NetworkPolicy when you want to control traffic flow between pods for security or compliance. For example:
- Limit database pods to accept traffic only from application pods.
- Isolate sensitive workloads from public-facing pods.
- Prevent pods from accessing external networks unless explicitly allowed.
This helps reduce attack surfaces and enforces clear communication boundaries inside your cluster.
Key Points
- NetworkPolicy controls pod-to-pod and pod-to-external communication.
- It uses labels to select pods and define allowed traffic.
- Without policies, all pods can communicate freely.
- Policies improve security by restricting traffic.
- They apply only if the network plugin supports them.