Session Affinity Using Nginx Ingress Controller: Kubernetes

Naman Gupta
3 min readMay 24, 2020

Most modern applications that I have deployed on Kubernetes works with a flow and does not require any caching layer to store data on web-server. In Other words most of these applications are stateless applications.

But there are some applications that are deigned to have save session data in temporary files(cookies) residing on the web server. The client session state is thus tied to particular web server, and all subsequent client requests must be sent to the same server — the HTTP sessions must be sticky. If this Client sessions breaks in between or this tightness breaks then this leads to client session to get expired and client will be rollout of server.

How do we solve this in Kubernetes world?

Thus we need something that helps client session to work with single server without any tightness hence Sticky Session aka Session Affinity Comes into role.

Enabling session stickiness with GCP Istio (beta) having its own challenges with this particular application hence we choose to use Nginx Ingress.

NGINX INGRESS CONTROLLER

Typically, As Discussed, Session Affinity is handled by load-balancers that direct traffic to a set of VMs (or nodes). In Kubernetes, however, we deploy services as pods, not VMS, and we require session affinity to direct traffic at pods. For this, we are using Service-type to be ClusterIP for Deployment with Nginx Ingress in frontend to balance the load.

The major Advantage of using Nginx Ingress Controller is, it meets all possible requirements that any ingress controller needs to have without adding any other features as sidecar. The Ingress Controller will have Session Affinity Implemented, once we configure session affinity for our ingress, it will respond to request with set-cookie header set by ingress-controller. The randomly generated cookie id will be map to served pod so that flow of all request will serve by same server.

Following is the ingress file with annotation for cookie set.

Following is the Service and Deployment file for application :-

After Deploying above all files with cookie set to nginx ingress controller we got the following result -:

When you hit the url for first time, the session cookie will automatically attached to response header and we can see the result whether Url Inspect Mode.

Or using Curl Method also, we can see the cookie attached to URL.

References.

--

--

Naman Gupta

Cloud/DevOps Eng. , I guide customers in their journey to cloud. My primary role is to work on Automation and Infrastructure part in a cost effective manner.