In Kubernetes, Network Policies are a way to control the communication between pods within a cluster. They allow you to define rules that specify how groups of pods are allowed or denied communication with each other.
Network Policies help enforce security and isolation within a Kubernetes cluster by controlling the flow of traffic between pods.
Selector Labels
Ingress and Egress Rules
Default Deny
Namespaces
Consider a scenario where you have a frontend application and a backend database in the same Kubernetes cluster. You want to restrict communication so that only the frontend pods can access the backend database, and other pods are not allowed to communicate with the database.
Here’s an example Network Policy for achieving this:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: my-namespace
spec:
podSelector:
matchLabels:
app: frontend
ingress:
- from:
- podSelector:
matchLabels:
app: backend
To apply the Network Policy to the cluster:
kubectl apply -f network-policy.yaml
Network Policies are enforced by the network solution implemented on the Kubernetes cluster. Some network solutions that support network policies:
The following does not support Network Policies: