2025-01-20

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’s Network Policies?

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

 Ingress = inbound traffic

 Egress = outbound traffic

Ingress and Egress example

These policies can be applied in pods and namespaces through selectors which selects a specific pod or namespace. And also, we can apply policies given a specific ip range (CIDR, ex: 10.0.4./16).

Hacking your policies

I was struggling myself 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 protect? Who connect? Where 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 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 can help you to understand network policies.