2025-01-18

Working with Network Policies in Kubernetes

My learning about network policies

Recently, I needed to understand how to use network policies in Kubernetes and I would like to share a simple hack that can help you with your own policies.

What are Network Policies?

It’s a functionality provided by Kubernetes that allow you to create a policy rules to allow or deny a connection. They are similar to firewall in Linux, where it’s possible to block ports, IPs and etc. Kubernetes defines a policy by following two concepts, Ingress and Egress.

 Ingress = inbound traffic

 Egress = outbound traffic

Ingress and Egress example

These policies can be applied to pods and namespaces through selectors, which target a specific pods or namespaces. Additionally, you can apply policies using a specific IP range (CIDR, e.g., 10.0.4./16).

Hacking your policies

I was struggling to create policies, especially when I needed to work with multiple conditions. So, I created a hack to simplify the process. I called this method as W.W.W (Who protects? Who connects? Where to send data?)

WWW Method

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: challenge
spec:
  podSelector:
    matchLabels:
      app: busybox-frontend # Who should be protected?
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - {} # Who can connect to busybox-frontend? 
  egress:
    - to:
      - podSelector:
          matchLabels:
            app: busybox-backend # Where protected should send data? 

Also, don’t forget to understand the difference between [], {} and leaving it empty:

ingress:
- {} # Allow all the traffic

ingress: [] # Block all the traffic

ingress: # Block all the traffic

That’s it guys! Thank you for reading my blog, I hope the tips shared here can help you to understand network policies.