Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes deployment multiple replicas - how to pass replica number to pod

Tags:

kubernetes

A new Kubernetes Deployment with 2+ replicas for high availability.

I want to be able to execute a command on the first pod only, let's say create a DB, and let the other replicas wait for the first one to complete.
To implement this, I just want to know in the pod if this is replica #1 or not.

So in the pod's entry point I can test:

if [ $REPLICA_ID -eq 1 ]; then 
    CreateDB
else
    WaitForDB
fi

Can this be done in Kubernetes?

like image 425
Eldad Assis Avatar asked Feb 05 '23 04:02

Eldad Assis


1 Answers

in Kubernetes a Deployment is considered stateless and therefore doesn't provide the feature you're looking for. You should rather look into StatefulSet and their features.

A StatefulSete.g. supports ordered creation and when combined with the generally available readinessProbe for you pods you could create the desired behaviour. Also the pod name is stable within a StatefulSet so your test could then be done with the hostname of the Pod.

like image 141
pagid Avatar answered Feb 11 '23 23:02

pagid