Selected topic

Network Policies

Networking

Prefer practical output? Use related tools below while reading.

In a Kubernetes cluster, Network Policies provide an additional layer of security and network management by controlling the incoming and outgoing traffic to/from pods. This is achieved through the use of label-based policies that define rules for network communication.

Key Concepts:


  1. Pods: Lightweight and portable units of computing, analogous to a virtual machine or a Docker container.
  2. Network Policies: Rules that control network access to/from pods based on labels and selectors.
  3. Selector: A way to match pods based on specific labels (key-value pairs).

Example Network Policy


Let's create an example network policy that allows only certain pods labeled as db to connect to a pod labeled as web.

yml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: web-allow-db-access
spec:
  podSelector:
    matchLabels:
      app: web
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: db

In this example:

  • We create a network policy named web-allow-db-access.
  • The policy applies to pods labeled as app=web (i.e., the web service).
  • The policy allows incoming traffic from pods labeled as app=db (i.e., the db service).

Traffic Flow:

When a pod is created or updated, Kubernetes checks if it matches any of the selectors in existing network policies. If a pod matches a selector, the policy's rules are applied to determine whether incoming/outgoing traffic is allowed.

In our example:

  • When a pod labeled as app=db tries to connect to the web service (labeled as app=web), the network policy allows the connection.
  • When any other pod attempts to connect to the web service, the network policy denies the connection, as it doesn't match the selector.

Benefits:

Network policies provide several benefits in a Kubernetes cluster:
  1. Security: Control incoming and outgoing traffic to/from pods based on labels and selectors.
  2. Flexibility: Define custom rules for network communication between pods.
  3. Scalability: Simplify security management as your cluster grows.
This is a basic example of using network policies in Kubernetes. For more information, I recommend exploring the official Kubernetes documentation or online resources like Kubecon tutorials or blog posts by experienced engineers.