Network Policies

[!NOTE] This module explores the core principles of Network Policies, deriving solutions from first principles and hardware constraints to build world-class, production-ready expertise.

1. The Problem: Default Allow

By default, Kubernetes is a flat network. Any Pod can talk to any other Pod, even across Namespaces. This is great for development but terrible for security. If an attacker compromises your frontend, they can directly scan your database.

2. The Solution: Network Policy

A NetworkPolicy is a firewall rule for Kubernetes. It allows you to restrict traffic based on:

  1. Pod Selector: Allow traffic only from Pods with label app: frontend.
  2. Namespace Selector: Allow traffic only from the production namespace.
  3. IP Block: Allow/Deny external IP ranges (CIDR).

[!WARNING] CNI Requirement: Network Policies are enforced by the CNI plugin (e.g., Calico, Cilium, Antrea). If you use a basic CNI like Flannel (without extra modules), Network Policies will have no effect.


3. Interactive: Firewall Visualizer

Test your firewall rules. Try to send packets between different tiers.

Database

Policy: Allow Frontend Only


4. Code Example: Zero Trust Policy

The best practice is to start with a Default Deny policy and then explicitly allow traffic.

Default Deny YAML
Allow Frontend YAML
# Deny ALL ingress traffic to all pods in this namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: database
spec:
  podSelector: {} # Selects all pods
  policyTypes:
  - Ingress
# Allow traffic from Frontend -> Database
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend
  namespace: database
spec:
  podSelector:
    matchLabels:
      app: db # Apply this rule to DB pods
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend # Only allow pods with app=frontend
  ports:
  - protocol: TCP
    port: 5432