简体   繁体   中英

MongoDB initialization in Docker Swarm

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:

  • split deployments and ensure to wait for database initialization before starting the server
  • deploy all together, but forcing the server to quit as long as queries to database throw exceptions or return empty collections

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM