Manage NodeJS and Databases connections delays between docker container
Problem
In a docker environnement, sometimes at startup or after a container upgrade, a database or any container service can take some times to initialize and such delay can prevent an other container to run.
For example if you start a docker compose with a microsoft sql server and a nodejs server, the first launch the microsoft sql server container may take 20 seconds to initialize its files structures, whereas nodejs server will take less than a second. So when nodejs will try to connect to the sql database, it will fail !
Solution 1:
if nodejs fails … start again (with docker ‘restart policy’) or with a node manager like pm2.
This is a very simple solution, but if you wait for 2 databases to initialize that might be a very poor efficient solution !
Solution 2 :
Use Events !
Events will be use to manage connection to databases. If the database is not ready, let’s create an other delayed event (setTimeout) to try later !
Once the database if connected, let’s emit an event to notify the main application that it can continue processing !
Let’s create ‘notifier.js’ to manage event beetween different modules:
In database module ‘mssql.js’, let’s manage database connection :
And finally in our main application ‘server.js’:
Multiples databases
A more complex problem is to wait for several databases for all been initialized before starting our server !
For this case, we will add to the previous solution like an event concentrator …
Considering that we have a mongoDB database … create a ‘mongodb.js”:
and let’s modify ‘index.js’ to add the concentrator:
Last minute :
I found an article that add an interesting solution to wait for a docker container to initialize. This solution can be interested for many case (and without changing your app) but it is not resolving long initalisation issues …