Labs ICT
⭐ Pro Login

Network Policies

Controlling traffic flow between pods

Network Policies β€” Controlling Pod Traffic

A NetworkPolicy specifies how groups of pods are allowed to communicate with each other and other network endpoints. By default, all pods in a Kubernetes cluster can communicate with each other β€” Network Policies let you lock that down.

Think of Network Policies as a firewall for your pods.

Default Behavior vs Network Policies


  Without Network Policies:
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Pod A   │◀───▢│  Pod B   │◀───▢│  Pod C   β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  Everything can talk to everything!

  With Network Policies:
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Pod A   │◀───▢│  Pod B   β”‚  X  β”‚  Pod C   β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  Only allowed traffic passes through

Creating a Network Policy


apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080

This policy says: only pods with label app: frontend can reach pods with label app: backend on port 8080. All other ingress traffic is blocked.

Blocking All Traffic


# Default deny all ingress traffic in a namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: default
spec:
  podSelector: {}    # Empty selector = applies to ALL pods
  policyTypes:
    - Ingress

This is a security best practice. Start by blocking everything, then selectively allow traffic with specific policies.

Common Patterns


# Allow traffic from specific namespaces
ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            env: production

# Allow traffic from a CIDR range
ingress:
  - from:
      - ipBlock:
          cidr: 10.0.0.0/8

# Allow egress (outgoing traffic)
egress:
  - to:
      - podSelector:
          matchLabels:
            app: database
    ports:
      - protocol: TCP
        port: 5432

Pod selectors β€” Target specific pods by label.

Namespace selectors β€” Target pods in specific namespaces.

IP blocks β€” Allow or deny specific IP ranges.

Requirements

Network Policies require a CNI (Container Network Interface) plugin that supports them. Popular options include Calico, Weave Net, and Cilium. Flannel does not support Network Policies.