Error connecting Node.js + MongoDB application within Docker containers I have a Node.js + MongoDB application that works perfectly without Docker. However, when I containerize it using Docker Compose, I encounter an error related to the timeout:
kinopoisk-node-app-1 | MongooseError: Operation `genres.count()` buffering timed out after 10000ms kinopoisk-node-app-1 | at Timeout. (/usr/src/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:23) kinopoisk-node-app-1 | at listOnTimeout (node:internal/timers:569:17) kinopoisk-node-app-1 | at process.processTimers (node:internal/timers:512:7) kinopoisk-node-app-1 | kinopoisk-node-app-1 | Node.js v18.14.2 kinopoisk-node-app-1 exited with code 1
Dockerfile:
FROM node:18.14.2
WORKDIR /usr/src/app
COPY . .
RUN npm install
EXPOSE 8000
CMD node server.js
docker-compose.yml:
version: '3'
services:
node-app:
build: .
image: kinopoisk:0.0.1
ports:
- 8080:8000
environment:
- MONGO_ADDRESS=mongodb://mongodb:27017/kinopoisk
mongodb:
image: mongo:4.4.6-bionic
Node.js connection code:
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGO_ADDRESS).then(() => {
return console.log("Connected to mongoDB")
}).catch((e) => {
console.log("Failed to connect to mongoDB")
})
Seed file:
const genres = require('./genres')
const data = [
'Комедии',
'Мультфильмы',
'Ужасы',
'Фантастика',
'Триллеры',
'Боевики',
'Мелодрамы',
'Детективы',
'Приключения',
'Фэнтези',
]
async function writeDataGenre(){
const length = await genres.count();
if(length==0){
data.map((item, index) => {
new genres({
name: item,
key: index
}).save()
})
}
}
module.exports = writeDataGenre
I expect the Node.js application to successfully connect to the MongoDB server within the Docker container without encountering the connection timeout error.