Kubernetes keep variables fixed to pods

11/21/2019

I have an application that has 3 pods and each pod needs a fixed variable name stored in each pod. So if everything is running fine, the three pods would have var1, var2, and var3 stored on the corresponding pods.

If the first pod gets replaced which has var1, how can I determine that the other 2 pods have var2 and var3, and thus know that the new pod should be assigned var1?

Can this be done with Stateful Sets?

-- William Ross
kubernetes
kubernetes-pod
kubernetes-statefulset

2 Answers

11/21/2019

I see two ways of doing that:

  1. Using StatefulSets:

For a StatefulSet with N replicas, each Pod in the StatefulSet will be assigned an integer ordinal, from 0 up through N-1, that is unique over the Set.

  1. Creating the Pods manually. Example:
apiVersion: v1
kind: Pod
metadata:
  name: memory-demo-3
  namespace: mem-example
spec:
  containers:
  - name: memory-demo-3-ctr
    image: polinux/stress

If you need your application to be aware of the Pod where it is running on, there is an interesting page in Kubernetes documentation: "Expose Pod Information to Containers Through Environment Variables".

Example:

apiVersion: v1
kind: Pod
metadata:
  name: mypod-var1
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      env:
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
-- victortv
Source: StackOverflow

11/21/2019

Using a StatefulSet you can extract this from the pod-name.

env:
  - name: podname
    valueFrom:
      fieldRef:
        fieldPath: metadata.name 

and then get it from the end of the name. The pods in a StatefulSet will be named <StatfulSetName>-<ordinal>, see pod-identity

-- Jonas
Source: StackOverflow