Search code examples
dockerdockerfiledocker-swarm

How to prevent a Docker Container to turn on while another Container in the same Service is trying to?


I want to prevent several containers to turn on together. i.e imagine that I have a service and I want to turn on 5 replicas of it.

Then They Should Act Like This:

container 1 starting ==> container 1 running and healthy ==> container 2 starts ==> container 2 running and healthy ==> container 3 starts ==> container 3 running and healthy ==> container 4 starts ==> container 4 running and healthy ==> container 5 starts ==> container 5 running and healthy.

I checked HEALTHCHECK, but I don't know exactly if it helps me in this case

Thank you


Solution

  • You can add another app container to act as coordinator.

    It is much related to this question.

    My idea is to have a shared Redis in which you have a shared-lock. So each new container that is starting query for that lock that is in the shared Redis, and when the lock is acquired, container finishes its startup, then release the lock.

    https://redis.io/topics/distlock

    Distributed locks are a very useful primitive in many environments where different processes must operate with shared resources in a mutually exclusive way.