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:

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:
  - Ingress
Click to expand and view more

Allow 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: 8080
Click to expand and view more

Advanced Patterns

Namespace Isolation

YAML
ingress:
- from:
  - namespaceSelector:
      matchLabels:
        environment: production
Click to expand and view more

External Traffic Control

YAML
egress:
- to:
  - ipBlock:
      cidr: 10.0.0.0/8
      except:
      - 10.0.0.0/24
Click to expand and view more

CNI Requirements

Network policies require a CNI plugin that supports them:

Testing Your Policies

Always test network policies before applying to production. Use tools like netcat or dedicated testing pods to verify connectivity.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut