How to Use Network Policy for Security in Kubernetes
NetworkPolicy in Kubernetes to control which pods can communicate with each other or external endpoints. Define rules specifying allowed ingress and egress traffic by selecting pods and namespaces with labels. Applying NetworkPolicy enhances cluster security by restricting unwanted network access.Syntax
A NetworkPolicy resource defines rules for pod communication. It has three main parts:
- podSelector: selects pods the policy applies to.
- ingress: rules for incoming traffic.
- egress: rules for outgoing traffic.
Each rule can specify allowed sources or destinations by pod labels, namespaces, or IP blocks.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: example-policy
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
egress:
- to:
- ipBlock:
cidr: 10.0.0.0/24
ports:
- protocol: TCP
port: 3306Example
This example allows only pods with label role: frontend to connect to pods labeled role: db on port 3306 (MySQL). It blocks all other traffic to the database pods.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-db
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 3306Common Pitfalls
1. No default deny: Without a NetworkPolicy, all traffic is allowed. To restrict traffic, you must create a policy that denies by default by specifying policyTypes and selectors.
2. Pod selector scope: If podSelector is empty, the policy applies to all pods in the namespace. Be careful to target only intended pods.
3. Missing ports: If ports are not specified, all ports are allowed. Specify ports to limit access.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: wrong-policy
spec:
podSelector: {}
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
# This allows all ports from frontend pods, which might be too open.
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: correct-policy
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 3306Quick Reference
- podSelector: Select pods to apply policy.
- policyTypes: Specify
Ingress,Egress, or both. - ingress/egress: Define allowed sources/destinations and ports.
- Empty podSelector: Applies to all pods in namespace.
- No policy: All traffic allowed by default.