Redirect traffic into same Pod with sessionAffinity

Kubernetes have feature to redirect traffic from same user into same Pod. The feature is sessionAffinity.

First, create a replica set with service.

apiVersion: extensions/v1beta1
kind: ReplicaSet
metadata:
  name: rs-kubia
  labels:
    app: kubia
spec:
  replicas: 5
  selector:
    matchLabels:
      apps: kubia
  template:
    metadata:
      labels:
        apps: kubia    
    spec:
      containers:
      - name: kubia
        image: luksa/kubia    
        ports:
        - containerPort: 8080
apiVersion: v1
kind: Service
metadata:
  name: kubia-svc
spec:
  selector:
    apps: kubia
  type: NodePort
  ports:
  - name: http
    port: 80    
    nodePort: 32600
    targetPort: 8080

let’s see the result

btech@zu-kubernetes-client:~/sessionAffinity$ kubectl get pod
NAME             READY   STATUS    RESTARTS   AGE
rs-kubia-cvvsv   1/1     Running   0          6m4s
rs-kubia-l9j8p   1/1     Running   0          6m4s
rs-kubia-nx2fh   1/1     Running   0          6m4s
rs-kubia-ql6fh   1/1     Running   0          6m4s
rs-kubia-tqfwr   1/1     Running   0          6m4s
btech@zu-kubernetes-client:~/sessionAffinity$ kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        16d
kubia-svc    NodePort    10.97.119.204   <none>        80:32600/TCP   4m39s

lets curl into the services

btech@zu-kubernetes-client:~/sessionAffinity$ while sleep 1; do curl 10.150.150.10:32600; done
You've hit rs-kubia-ql6fh
You've hit rs-kubia-nx2fh
You've hit rs-kubia-tqfwr
You've hit rs-kubia-cvvsv
You've hit rs-kubia-ql6fh
You've hit rs-kubia-ql6fh
You've hit rs-kubia-ql6fh
You've hit rs-kubia-nx2fh
You've hit rs-kubia-l9j8p
You've hit rs-kubia-nx2fh
You've hit rs-kubia-ql6fh
You've hit rs-kubia-cvvsv

look, your request is handle by many pod that belong to the service. We want to make sure that a single client is handle by only single pod, lets update the service

apiVersion: v1
kind: Service
metadata:
  name: kubia-svc
spec:
  sessionAffinity: ClientIP
  selector:
    apps: kubia
  type: NodePort
  ports:
  - name: http
    port: 80    
    nodePort: 32600
    targetPort: 8080

trying to curl again

btech@zu-kubernetes-client:~/sessionAffinity$ while sleep 1; do curl 10.150.150.10:32600; done
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p
You've hit rs-kubia-l9j8p

Comments are closed.