I have a task that I need to make sure it only runs once in my dockerized environment (managed by k8s), running the post-upgrade script is one example.
Because each dockerized app can run the task and the docker containers may restart, I believe I need to store a state that indicating whether the task has run or not in a database, not just in memory. I also need to provide some locking mechanism to prevent multiple docker containers from running the task more than once.
The simple way is to use row lock to serialize access, only one dockerized app can read/write the record. For example just use sql SELECT ... FOR UPDATE
, so the first docker container who gets the lock will check and run the task if necessary. All the other docker containers will just wait and get the set record later.
But I fell I can better than just serialize access. For example for the database supports SELECT ... FOR UPDATE NOWAIT
I can use NOWAIT
, so if a docker instance fails to get the lock that means one docker instance has got the lock and maybe have run the task, so it can just return, no need to wait for the lock then.
But not every database supports NOWAIT
so I am thinking about how to implement a homemade solution to do that. The goal to make sure running the task only once.
Any suggestion ?