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
- affinity: enables and sets the affinity type in all Upstreams of an Ingress. This way, a request will always be directed to the same upstream server.
- affinity-mode: defines the stickiness of a session. Setting this to balanced (default) will redistribute some sessions if a deployment gets scaled up, therefore rebalancing the load on the servers. Setting this to persistent will not rebalance sessions to new servers, therefore providing maximum stickiness.
- session-cookie-name: set cookie name, the default is to create a cookie named 'INGRESSCOOKIE'.
- session-cookie-secure: Set the cookie as secure regardless the protocol of the incoming request.
- session-cookie-max-age: Time until the cookie expires, corresponds to the Max-Age cookie directive.
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