Sign In

Curriculum 26: Security Best Practices

Network Policies

20 min · 35 XP

Network Policies

Network policies act as firewalls for pod-to-pod communication. By default, all pods can communicate freely. Network policies restrict traffic based on labels, namespaces, and ports.

Basic Ingress Policy

Restrict which pods can send traffic to your application:

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

Egress Rules

Control outbound traffic from pods:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: restrict-egress
spec:
  podSelector:
    matchLabels:
      app: api-server
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: database
      ports:
        - protocol: TCP
          port: 5432
    - to: # Allow DNS
        - namespaceSelector: {}
      ports:
        - protocol: UDP
          port: 53

Namespace Selectors

Allow traffic from specific namespaces:

ingress:
  - from:
      - namespaceSelector:
          matchLabels:
            environment: staging
        podSelector:
          matchLabels:
            app: tester

Managing with kubectl

# Apply a network policy
kubectl apply -f network-policy.yaml

# List policies in a namespace
kubectl get networkpolicies -n production

# Inspect a policy
kubectl describe networkpolicy allow-frontend-only -n production

# Default deny all ingress in a namespace
kubectl apply -f - <<'POLICY'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
spec:
  podSelector: {}
  policyTypes:
    - Ingress
POLICY

Always start with a default-deny policy, then explicitly allow required communication paths.