Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service selection from only one pod of one statefulset

It is possible to create a service that only points to a pod, created by a statefulset?

The solutions that make me would be:

  • Put as a provider on behalf of the pod.
  • Dynamic labels with the name of the pod.
like image 252
jbelenus Avatar asked Jan 08 '18 12:01

jbelenus


2 Answers

As per Kubernetes 1.9 you can use: statefulset.kubernetes.io/pod-name

From the documentation:

"When the StatefulSet controller creates a Pod, it adds a label, statefulset.kubernetes.io/pod-name, that is set to the name of the Pod. This label allows you to attach a Service to a specific Pod in the StatefulSet."

https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-name-label

like image 64
Adrián Deccico Avatar answered Nov 15 '22 11:11

Adrián Deccico


You can use the ordinal value of statefulset pod to label a pod.

I would use kubectl in initContainer to label the pods from within the pods created by statefulset and use that label in service selector spec.

example init container:

initContainers:
  - name: set-label
    image: lachlanevenson/k8s-kubectl:v1.8.5
    command:
      - sh
      - -c
      - '/usr/local/bin/kubectl label pod $POD_NAME select-id=${HOSTNAME##*-} --server=https://kubernetes.default --token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) --certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt -n $POD_NAMESPACE'
    env:
      - name: POD_NAMESPACE
        valueFrom:
          fieldRef:
            fieldPath: metadata.namespace
      - name: POD_NAME
        valueFrom:
          fieldRef:
            fieldPath: metadata.name

example service selector:

selector:
  app: my-app
  select-id: <0|1|2 ordinal value>
like image 33
Itamar Lavender Avatar answered Nov 15 '22 11:11

Itamar Lavender