kubernetes kubernetes/cka kubernetes/networking

Network Policies | Kubernetes
Kubernetes Network Policy - Guide with Examples
kubernetes-network-policy-recipes

Core Idea

Network Policies are firewall rules for pods: declare which pods may exchange traffic, and enforcement only happens if the cluster’s CNI implements them.

  • They select pods and allow or deny traffic flows, limiting the damage when one application in the cluster is compromised.
  • Policies only work with a CNI that supports them; the note lists supported network policy CNIs.
  • Recipes for common shapes (deny all, allow specific pairs) live in the linked policy recipe collection.

Network Policies are a mechanism for controlling network traffic flow in Kubernetes clusters.
They allow you to define which of your Pods are allowed to exchange network traffic. You should use them in your clusters to prevent apps from reaching each other over the network, which will help limit the damage if one of your apps is compromised.

There are three different ways to identify target endpoints:

  • Specific Pods (Pods matching a label are allowed)
  • Specific Namespaces (all Pods in the namespace are allowed)
  • IP address blocks (endpoints with an IP address in the block are allowed)

Network Policies represent layer 3/4 controls. They work with IP addresses and port numbers at the network transport level

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
 name: db-policy
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: api-pod
    ports:
    - protocol: TCP
      port: 3306



Network Policy Supported CNI

Network Policy SupportedNetwork Policy UnSupported
Kube-RouterFlannel
Calico
Canal

Canal combines Flannel and Calico, allowing you to use Flannel for networking while leveraging Calico’s network policy features.

Network Policy in K3s

By default, K3s uses Flannel as its Container Network Interface (CNI), which does not support network policies.
However, K3s includes an embedded network policy controller based on Kube-router, which enables network policy functionality. This means that while Flannel itself doesn’t support network policies, K3s provides the necessary components to enforce them through the Kube-router’s netpol controller
Networking Services | K3s
Basic Network Options | K3s
GitHub - cloudnativelabs/kube-router: Kube-router, a turnkey solution for Kubernetes networking.