I have a simple NodeJS app with connection to mongodb which are all started using docker compose. The problem it that if mongo is not initiated yet - NodeJS app throws an error that it cannot connect to mongodb:
nodejs-app | Server running...
nodejs-app | MongoNetworkError: failed to connect to server [mongo:27017] on first connect [Error: connect ECONNREFUSED 192.168.192.2:27017
When I restarting nodejs app manually - it connecting successfully as mongo already initialized:
nodejs-app | Server running...
nodejs-app | MongoDB Connected
My docker compose file:
version: '3.7'
services:
mongo:
container_name: mongo
restart: always
image: mongo:4.2.0
volumes:
- ./data:/data/db
ports:
- '27017:27017'
networks:
- nodejs-mongo
nodejs-app:
container_name: nodejs-app
restart: always
build: test-files
ports:
- '3000:3000'
environment:
- MONGO_PORT=27017
depends_on:
- mongo
networks:
- nodejs-mongo
networks:
nodejs-mongo:
My question is - how to check that mongo port available prior to starting nodejs-app container to suppress connection errors of nodejs-app?
Well, have done it this way in dockerfile, using docker-compose-wait:
## Add the wait script to the image
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.8.0/wait /wait
RUN chmod +x /wait
## Launch the wait tool and then your application
CMD /wait && node index.js
COPY . /usr/src/app