Advanced Network Policy Patterns

Advanced Network Policy Patterns

Complex applications require sophisticated Network Policy patterns beyond basic allow/deny rules. Namespace-based segmentation provides coarse-grained isolation between different environments or tenants. By labeling namespaces and using namespace selectors, organizations can implement environment isolation, ensuring production workloads cannot communicate with development systems.

Service mesh integration enhances Network Policy capabilities with layer 7 controls. While Network Policies operate at layers 3 and 4, service meshes like Istio or Linkerd provide application-layer filtering. Combining Network Policies with service mesh policies creates defense-in-depth, with network-layer controls providing baseline security and service mesh policies enabling fine-grained application controls.

# Multi-tier application network policies
# Frontend tier - only accepts traffic from ingress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: frontend-netpol
  namespace: webapp
spec:
  podSelector:
    matchLabels:
      tier: frontend
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: ingress-nginx
    ports:
    - protocol: TCP
      port: 80
  egress:
  - to:
    - podSelector:
        matchLabels:
          tier: backend
    ports:
    - protocol: TCP
      port: 8080

---
# Backend tier - accepts from frontend, connects to database
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-netpol
  namespace: webapp
spec:
  podSelector:
    matchLabels:
      tier: backend
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          tier: frontend
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - podSelector:
        matchLabels:
          tier: database
    ports:
    - protocol: TCP
      port: 5432

---
# Database tier - only accepts from backend
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: database-netpol
  namespace: webapp
spec:
  podSelector:
    matchLabels:
      tier: database
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          tier: backend
    ports:
    - protocol: TCP
      port: 5432

Cross-namespace communication policies address microservices architectures where services span multiple namespaces. Shared services like authentication or logging require careful policy design to allow access from multiple namespaces while maintaining security. Namespace labels enable dynamic policy updates as new namespaces are created, avoiding policy proliferation.