Kubernetes Service Networking using IPtables
How Kubenetes services like ClusterIP or NodePort work behind the scenes.
Kube-Proxy is the component responsible for setting up all the networking for your service. It runs as a daemon set on each node and configures the routing rules for kubernetes services.
Behind the scene the kube-proxy works with the kernel’s iptable rules (If the proxy is running in iptable mode) and modifies the prerouting chain. Any ip packet that enters the kernel stack first goes through this chain where the service ip is resolved to the pod ip.
Kube proxy listens to the api server continously and if there are any changes to the pods(ips) or if there is a new service it will make those changes to the iptable rules on each of the nodes in the cluster.
In the below figure we have 2 services deployed in our cluster. nginx-service is a clusterIP service and service1 is a NodePort type of service and they have the respective pod ip listed in the endpoints output.
Lets look below at the iptable rules for the clusterIP service. For this you will have to login to any of the nodes in the cluster and run the below commands. Open the below diagram by clicking in a separate tab for full view.
We can check the prerouting iptables chain using
iptables -t nat -L PREROUTING
Which shows us the KUBE-SERVICES chain, point (1) from the diagram. Lets describe that
iptables -t nat -L KUBE-SERVICES
Now you can see the service specific chains. for our nginx-service we have one at (4).
Lets describe that.
iptables -t nat -L KUBE-SVC-V2OKYYMBY3REGZOG
Now you can see the pod specific ips 10.244.1.4:80 and 10.244.1.6:80 as a output, which matches with our service enpoints from the first image. So all the traffic destined for the service would be forwarded to either of these 2 ips. (6)
Similarly you can check these rule for NodePort service as well.
Thank You!


