<p>Suppose we have a service replicated to several pods. The first request to the service should be  randomly(or by a load balancing algorithm) routed to a pod and the mapping 'value_of_certain_header -> pod_location' should be saved somehow so next request will be routed to specific pod.</p>

<p>Are there any Ingress controllers or other approaches for Kubernetes to implement stickiness to specific pod by request header? Basically I need the same behaviour that haproxy does with its sticky tables.</p>

<p>Kubernetes Ingress works on OSI Layer7, so it can take into account HTTP headers, but it only forwards traffic to Kubernetes Services, not to Pods.</p>

<p>Unfortunately, Kubernetes Services in turn, can't deliver traffic to specific pods depending on HTTP headers, because Service is basically set of iptables rules that deliver traffic to pod, only analyzing data on OSI Layer4 (IP address, tcp/udp, port number).</p>

<p>For example, let's look at kube-dns service iptables rules:</p>

<pre><code># kube-dns service
-A KUBE-SERVICES -d 10.96.0.10/32 -p udp -m comment --comment "kube-system/kube-dns:dns cluster IP" -m udp --dport 53 -j KUBE-SVC-TCOU7JCQXEZGVUNU 
# random load balancing traffic between pods
-A KUBE-SVC-TCOU7JCQXEZGVUNU -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-AALXN3QQZ3U27IAI
-A KUBE-SVC-TCOU7JCQXEZGVUNU -j KUBE-SEP-WTX2W5TQOZGP42TM
# dns pod 1
-A KUBE-SEP-AALXN3QQZ3U27IAI -p udp -m udp -j DNAT --to-destination 10.244.0.16:53
# dns pod 2
-A KUBE-SEP-WTX2W5TQOZGP42TM -p udp -m udp -j DNAT --to-destination 10.244.0.17:53
</code></pre>

<p>I can imagine only one realistic way to deliver traffic to specific pod based on HTTP Headers. </p>

<ol>
<li><p>Configure custom Ingress controller which can set the headers for each Client session and use known DNS names of pods as a back-end destination points. I can't recommend particular solution, so in worst case it could be created using <a href="https://www.geeksforgeeks.org/creating-a-proxy-webserver-in-python-set-1/" rel="nofollow noreferrer">some examples</a>.</p></li>
<li><p>Kubernetes StatefulSet creates Pods with predictable names like statefulset-name-0, statefulset-name-1, etc. Corresponding Headless Service (ClusterIP: None) creates DNS names for each Pod.</p></li>
</ol>

<p>For example, for StatefulSet nginx-ss with three replicas, three pods would be created and Service nginx-ss would create three DNS A records for Pods:</p>

<pre><code>nginx-ss-0   1/1     Running     10.244.3.72    
nginx-ss-1   1/1     Running     10.244.3.73    
nginx-ss-2   1/1     Running     10.244.1.165   

nginx-ss-0.nginx-ss.default.svc.cluster.local. 5 IN A 10.244.3.72
nginx-ss-1.nginx-ss.default.svc.cluster.local. 5 IN A 10.244.3.73
nginx-ss-2.nginx-ss.default.svc.cluster.local. 5 IN A 10.244.1.165
</code></pre>
