- Network Policies allows you to control how Pod communicate with each other and with other network entities
Definitions:
- Ingress traffic: Traffic coming into a pod
- Egress traffic: Traffic leaving a pod
Why Network Policies?
- By default, Kubernetes allows all traffic between pods, but by defining network policies can let you restrict this communication.
- Let’s say the team wants to ensure:
- The frontend cannot access the database directly.
- Only the API server should be able to talk to the DB on port 3306.
- This is where Network Policies comes into play. They allow you to:
- Define rules about who can send traffic to a pod (Ingress).
- Define rules about where a pod can send traffic (Egress).
How Network Policies Work
- Network Policies are defined using:
podSelector
: Which pods the policy applies topolicyTypes
: EitherIngress
,Egress
, or bothrules
: Specific rules that allow traffic based on pod labels and ports
- Important:
- Policies deny all traffic by default unless it is explicitly allowed.
Example Use Case
To allow only API server to talk to the DB server on port 3306:
- Label the DB server:
server=db
- Label the API server:
server=api
- Create a NetworkPolicy like:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-policy
spec:
podSelector:
matchLabels:
server: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
server: api
ports:
- protocol: TCP
port: 3306
Granular NetworkPolicy
- Above policy would allow any API pod with matching label in any namespace
Add namespaceSelector
ingress:
- from:
- podSelector:
matchLabels:
server: api
- namespaceSelector:
matchLabels:
team: team-a
Allow External Access
- External sources can’t be matched using pod/namespace selectors
- Use
ipBlock
to allow access from an IP address
from:
- ipBlock:
cidr: 192.168.5.10/32
Common Mistake: Dashes Create New Rules
- These are two (OR condition):
from:
- podSelector: {...}
- namespaceSelector: {...}
- But below means both must be satisfied (AND condition):
from:
- podSelector: {...}
namespaceSelector: {...}
⬅️ | Ingress ➡️