Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rcarrata/b0258b0c20d55568a4827c12fb4d923e to your computer and use it in GitHub Desktop.
Save rcarrata/b0258b0c20d55568a4827c12fb4d923e to your computer and use it in GitHub Desktop.
Enable Session Affinity (a.k.a Sticky Session) to Kubernetes service

https://stackoverflow.com/questions/48993286/is-it-possible-to-route-traffic-to-a-specific-pod?rq=1

You can guarantee session affinity with services, but not as you are describing. So, your customers 1-1000 won't use pod-1, but they will use all the pods (as a service makes a simple load balancing), but each customer, when gets back to hit your service, will be redirected to the same pod.

Note: always within time specified in (default 10800):

service.spec.sessionAffinityConfig.clientIP.timeoutSeconds

This would be the yaml file of the service:

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

If you want to specify time, as well, this is what needs to be added:

  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10

Note that the example above would work hitting ClusterIP type service directly (which is quite uncommon) or with Loadbalancer type service, but won't with an Ingress behind NodePort type service. This is because with an Ingress, the requests come from many, randomly chosen source IP addresses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment