😶‍🌫️

Docker上のMongoDBに接続するときにMongoServerSelectionErrorが出て接続できない

2023/03/02に公開

経緯

Docker上でNuxt3 x MongoDBのアプリケーションを作成しようとしたが、Node.jsからMongoDBに接続する際に以下のエラーが出て接続できなかった。

[nitro] [dev] [unhandledRejection] MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017                                                   09:04:21
    at Timeout._onTimeout (/app/node_modules/mongodb/lib/sdam/topology.js:277:38)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { '127.0.0.1:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

docker-compose.ymlの内容

services:
  app:
    build: .
    volumes:
      - ./app:/app:cached
      - node_modules:/app/node_modules
    working_dir: "/app"
    ports:
      - 3000:3000
    tty: true
    environment:
      - HOST=0.0.0.0
      - port=3000
      - CHOKIDAR_USEPOLLING=true
    depends_on:
      - mongo

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: username
      MONGO_INITDB_ROOT_PASSWORD: password
    ports:
      - 27017:27017
    volumes:
      - ./db:/data/db
      - ./configdb:/data/configdb

  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: username
      ME_CONFIG_MONGODB_ADMINPASSWORD: password
      ME_CONFIG_MONGODB_SERVER: mongo
    depends_on:
      - mongo

volumes:
  node_modules:

データベースに接続するコード

import { MongoClient } from 'mongodb'

const url = 'mongodb://username:password@localhost:27017'
const client = new MongoClient(url)

(async () => {
    await client.connect()
})()

export const db = client.db('dbName')

解決策

URLのlocalhostmongoに変更する必要がある。

const url = 'mongodb://username:password@mongo:27017'

具体的にはmongoでなはく、docker-compose.ymlに書いているMongoDBのサービス名。

mongo: # この部分
  image: mongo
  restart: always

Discussion