Your startup script should not initialise or monitor the replicaset; those should be manual tasks.
You should bear in mind that:
- initiating a replica set is strictly a one-off job; once it is initiated, the MongoDB service, when restarted, will continue being part of the same replica set.
- a replica set normally contains several nodes which should be interchangable; if each of them tries to initialise the replica set on startup, they will throw errors
- restarting a service is normal, expected behaviour; for example when you upgrade to the next version of MongoDB, or after patches to your server host require a reboot, or after a power outage
- if your script tries to initialise an already-initialised replica set each time it starts the MongoDB service, it will throw errors
I strongly recommend that you make three changes:
- Let your mongo container just run mongo, without the steps to initiate and monitor the replica set.
- If you want to run a replica set, initiate it carefully and in a controlled manual way; ditto if you want to add / remove nodes, or reconfigure.
- If you want to monitor the health of your replica set, use a separate tool to do that; let the mongo service just do its ordinary job.