3
votes

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?

2

2 Answers

4
votes

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.

2
votes

Instead of the accepted answer, wouldn't an init container fit your problem description better?

Add some kind of semaphore system (if needed) to ensure it is executed correctly?