Network Policy in Kubernetes

Pre-requisites:

  • Minikube setup
  • Basic idea on deployments and pods

Goals:

  • Understand the basics and the use cases on the Network Policy
  • You will get hands-on practice with network policies to control the traffic between services running on Kubernetes.

What is Network Policy in Kubernetes ?

  • Pods with a specific label
  • Pods belonging to a namespace with a particular label
  • A combination of both rules restricts the selection of labelled pods in labelled namespaces
  • Specific IP ranges

Ingress and Egress :

Traffic coming to the Kubernetes pod
Ingress Traffic
Traffic goes from the Kubernetes pod
Egress Traffic

Network Policy in Action

Running Minikube with the network plugin (Calico) :

minikube start --network-plugin=cni --cni=calico
Kubernetes running with Calico CNI in Minikube
kubectl get pods -l k8s-app=calico-node -n kube-system
List down the calico pods

Checking default allow-all rule

Default behaviour of pod communication
Default behaviour of pod communication
  • frontend service => frontend pod
  • backend service => backend pod
  • db service => mysql pod
kubectl apply -f network-policy-demo.yaml
Apply the YAML file to create pods and services
Running 3 pods and 3 services
Checking communication to backend service from frontend pod before applying Policy
apt update && apt install telnet -y
telnet db 3306
Database pod is accessible from frontend pod before applying Policy
Database pod is accessible from backend pod before applying Policy
Network policy for the Ingress traffic to the Database pod
Network policy for the Ingress traffic to the Database pod
  • spec.podSelector defines the pod on which we are going to apply the policy. In this case, it’s MySQL database pod.
  • spec.ingress[].from[].podSelector defines the only pod from which ingress traffic should be accepted.
  • spec.ingress[].ports[] defines the only port number on which ingress traffic should be accepted.
kubectl apply -f db-netpol.yaml
Apply the Network policy and verify
Database pod is accessible from backend pod after applying Policy
Database pod is not accessible from frontend pod after applying Policy

References

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store