Network Policies are Kubernetes resources that control traffic flow between pods. By default, Kubernetes allows all pod-to-pod communication, which can be dangerous in a multi-tenant environment.
Why Network Policies Matter
Without network policies, a compromised pod can:
- Scan the internal network
- Access databases directly
- Communicate with other services it shouldn’t
Creating Your First Network Policy
Default Deny All Ingress
Start by denying all incoming traffic:
YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: production
spec:
podSelector: {}
policyTypes:
- IngressAllow Specific Traffic
Then explicitly allow required communication:
YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080Advanced Patterns
Namespace Isolation
YAML
ingress:
- from:
- namespaceSelector:
matchLabels:
environment: productionExternal Traffic Control
YAML
egress:
- to:
- ipBlock:
cidr: 10.0.0.0/8
except:
- 10.0.0.0/24CNI Requirements
Network policies require a CNI plugin that supports them:
- Calico
- Cilium
- Weave Net
- Antrea
Testing Your Policies
Always test network policies before applying to production. Use tools like netcat or dedicated testing pods to verify connectivity.