1
resposta

[Dúvida] Docker + NodeJs + MongoDB

Tenho um projeto multicontainer com o Mongo, React e NodeJS. Ao tentar realizar a conexão com Mongoose, retorna o erro de connection timeout. Alguém sabe como posso resolver?

Versão do node: v20.3.0 Versão do Mongoose: "^7.3.0" Insira aqui a descrição dessa imagem para ajudar na acessibilidadeArquivo docker-compose.yml

# docker compose version which is currently 3.8
version: "3.8"

# services : is a list of our container
services:
  mongodb:
    container_name: mongodb
    image: "mongo"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=root
      - MONGO_INITDB_DATABASE=database
    restart: always
    ports:
      - "23000:27017"
    volumes:  # our mongodb depends on volume to keep the data alive.
      - data:/data/mongodb

  server:
    container_name: server
    build: ./server
    restart: always
    ports:
      - "24000:8080"
    volumes:
      - ./server:/app
    networks:
      - db
    depends_on:
      - mongodb

  client:
    container_name: client
    build: ./client
    restart: always
    ports:
      - "25000:3000"
    volumes:
      - ./client:/app
    stdin_open: true
    tty: true
    networks:
      - db

volumes:
  data:
networks:
  db:
    driver: bridge

Arquivo de configuração do banco (database.js)

const mongoose = require('mongoose')
require('dotenv').config()

const user = process.env.DB_USER
const pass = process.env.DB_PASSWORD
const host = process.env.DB_HOST
const port = process.env.DB_PORT

mongoose.connect(`mongodb://${user}:${pass}@${host}:${port}`)

let database = mongoose.connection

module.exports = { database }

Arquivo raiz do node (app.js)

const { router } = require('./src/routes/routes')
const { database } = require('./src/config/database')
const express = require('express')
const expressValidator = require('express-validator')
const app = express()
const PORT = process.env.SERVER_PORT

global.blacklist = []

app.use(express.json())
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Methods', '*')
    res.setHeader('Access-Control-Allow-Headers', '*')
    res.setHeader('Access-Control-Allow-Credentials', true)
    next()
})
app.use(router)


database.on('error', console.log.bind(console, 'Connection error'))
database.once('open', () => { console.log('Successful connection') })


app.listen(PORT, console.log(`Server running on port ${PORT}`))

module.exports = { app }
1 resposta

no seu compose client e server estão na mesma network mas o mongodb não está. já tentou colocar ele na mesma network que os outros dois serviços?