I'm trying to dockerize Node.js application which connects to MongoDB using mongoose. It succeeds anytime I run node index.js
from the shell when the connection URL is: mongodb://localhost:27017/deposit
.
If I restart my computer and then try to run the dockerized project (with mongo
instead of localhost
in url) with the command docker-compose up
it fails to connect to MongoDB. But after I try again the same command, then it succeeds.
So my question is why node cannot connect to MongoDB on first try after the computer is restarted?
PS. Docker is running when I'm trying it
connection.js
const mongoose = require('mongoose');
const connection = "mongodb://mongo:27017/deposit";
const connectDb = () => {
mongoose.connect(connection, {useNewUrlParser: true, useUnifiedTopology: true}).then(res => console.log("Connected to DB"))
.catch(err => console.log('>> Failed to connect to MongoDB, retrying...'));
};
module.exports = connectDb;
Dockerfile
FROM node:latest
RUN mkdir -p /app
WORKDIR /app
#/usr/src/app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 7500
# ENTRYPOINT ["node"]
CMD ["node", "src/index.js"]
docker-compose.yml
version: "3"
services:
deposit:
container_name: deposit
image: test/deposit
restart: always
build: .
network_mode: host
ports:
- "7500:7500"
depends_on:
- mongo
mongo:
container_name: mongo
image: mongo
volumes:
- /data:/data/db
network_mode: host
ports:
- '27017:27017'