Kubernetes Network Policies

Jul 14, 2024

Kubernetes Network Policies

Introduction

  • Kubernetes network policies can control traffic flow between pods at the IP address or port level (OSI Layer 3/4).
  • Useful in multi-tenant clusters or clusters with multiple environments (development, testing, production).

Pod Networking Requirements

  • Each pod gets its own IP address.
  • All pods can communicate with each other without Network Address Translation (NAT).
  • IP addresses of pods remain consistent across the cluster.
  • Cross-namespace communication is possible by default.

Real-World Scenario

  • Multiple applications (App A and App B) and a database (Redis DB) running in different namespaces.
  • By default, all pods can communicate with each other.
  • Using network policies: Pods in App A can communicate with the DB, but pods in App B cannot.

Network Policies

  • Control traffic flow at IP/port level between pods.
  • Policy is defined using Kubernetes manifests.
  • Policies apply to pods based on labels.

Implementing Network Policies

  1. *Commands to Check Pods and IPs:
    • kubectl get pods -A : Show all pods across namespaces.
    • kubectl get pods -A -owide : Show IP addresses of pods.
  2. *Example Commands for Ping Demo:
    • From Namespace A pod to Namespace B pod:
      kubectl -n namespace-a exec -it pod-name -- curl <namespace-b-pod-ip>
      
    • From Namespace A pod to Namespace C pod using similar command.
  3. *Defining Labels:
    • kubectl describe namespace namespace-a : Shows labels for a namespace.

Network Policy YAML

  • Example YAML:
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: allow-app-a
      namespace: namespace-b
    spec:
      podSelector:
        matchLabels:
          environment: test
      policyTypes:
      - Ingress
      ingress:
      - from:
        - namespaceSelector:
            matchLabels:
              myspace: namespace-a
    
  • Apply with kubectl apply -f <file-name>.

Demo Recap

  • Installed Calico for network policy enforcement.
    • Basic commands to install Calico.
  • Successfully tested network policy:
    • Namespace C pod unable to ping Namespace B pod.

Advanced Options

  • Restrict traffic using IP address blocks or pod labels.
  • *'Or' Conditions in Policies:
    • Use dashes (-) in front of selectors for 'or' conditions.
  • *'And' Conditions in Policies:
    • No dashes for 'and' conditions (all conditions must be met).

Kubernetes Documentation Example

  • Egress and Ingress can control specific ports.
  • Example network policy with ingress/egress controls.

Additional Resources

  • Sample network policy stored in GitHub repository for testing.
  • Mentioned Udemy course for deeper learning on Kubernetes and DevOps.

Conclusion

  • Like, subscribe, and comment on requests for future videos.