Session Affinity Settings for multiple Pods exposed by a single service Session Affinity Settings for multiple Pods exposed by a single service kubernetes kubernetes

Session Affinity Settings for multiple Pods exposed by a single service


Main concept of Session Affinity is to redirect traffic from one client always to specific node. Please keep in mind that session affinity is a best-effort method and there are scenarios where it will fail due to pod restarts or network errors.There are two main types of Session Affinity:

1) Based on Client IP

This option works well for scenario where there is only one client per IP. In this method you don't need Ingress/Proxy between K8s services and client. Client IP should be static, because each time when client will change IP he will be redirected to another pod.

To enable the session affinity in kubernetes, we can add the following to the service definition.

service.spec.sessionAffinity: ClientIP

Because community provided proper manifest to use this method I will not duplicate.

2) Based on Cookies

It works when there are multiple clients from the same IP, because it´s stored at web browser level. This method require Ingress object. Steps to apply this method with more detailed information can be found here under Session affinity based on Cookie section.

  • Create NGINX controller deployment
  • Create NGINX service
  • Create Ingress
  • Redirect your public DNS name to the NGINX service public/external IP.

About mapping ClientIP and POD, according to Documentation kube-proxy is responsible for SessionAffinity. One of Kube-Proxy job is writing to IPtables, more details here so thats how it is mapped.

Articles which might help with understanding Session Affinity:https://sookocheff.com/post/kubernetes/building-stateful-services/https://medium.com/@diegomrtnzg/redirect-your-users-to-the-same-pod-by-using-session-affinity-on-kubernetes-baebf6a1733b


follow the service reference for session affinity

kind: ServiceapiVersion: v1metadata:  name: my-servicespec:  selector:    app: my-app  ports:  - name: http    protocol: TCP    port: 80    targetPort: 80  sessionAffinity: ClientIP  sessionAffinityConfig:    clientIP:      timeoutSeconds: 10000