Kubernetes sticky sessions


Sticky sessions

By ingress

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: test
  annotations:
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/affinity-mode: "balanced" #balanced|persistent
    nginx.ingress.kubernetes.io/session-cookie-name: "cookie-name"
        nginx.ingress.kubernetes.io/session-cookie-secure: "true"
        nginx.ingress.kubernetes.io/session-cookie-max-age: 120
spec:
  rules:
    - host: test.io
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: test
                port:
                  number: 8080

By kubernetes service

Session affinity

In these proxy models, the traffic bound for the Service's IP:Port is proxied to an appropriate backend without the clients knowing anything about Kubernetes or Services or Pods.

If you want to make sure that connections from a particular client are passed to the same Pod each time, you can select the session affinity based on the client's IP addresses by setting .spec.sessionAffinity to ClientIP for a Service (the default is None).

Session stickiness timeout

You can also set the maximum session sticky time by setting .spec.sessionAffinityConfig.clientIP.timeoutSeconds appropriately for a Service. (the default value is 10800, which works out to be 3 hours).

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
   sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 60

or

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
   sessionAffinityConfig: ClientIP