I have a NodeJS server which have to connect to a MongoDB instance, both running as docker containers in a Swarm environment. The database contains collections created and filled at startup using the default procedure.
I would like to ensure that NodeJS service will start when database completed its initialization (and not as soon as it is "up & running"), but I do not understand how should I do this in Swarm. The only options I thought are:
Is there any other approach (either on Docker, MongoDB or NodeJS side) that I should use to handle this "synchronization"?
You can always use docker compose depends on function with some command too. Which continuously check if the entries are in the database or not. But may be you need an overlay driver in order to make it work with swarm.
driver: overlay
Example:
depends_on:
- "db"
command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"]
Example wait-for-it.sh
#!/bin/sh
# wait-for-postgres.sh
set -e
host="$1"
shift
cmd="$@"
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec $cmd
UPDATE: : Depends on function is not honored in Docker-Swarm because the service get restarts automatically in it. With this bash script you can manually hold the service untill entries are populated in DB. Change this bash script according to your need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.