docker NestJS容器与MongoDB容器连接的问题

wgmfuz8q  于 2023-05-06  发布在  Docker
关注(0)|答案(1)|浏览(170)

我有一个使用Docker容器的项目:

  1. API容器(NestJS)
    1.蒙戈集装箱
    NestJS不想连接到mongoDB,而是连接到mongoDB Atlas。什么都试过了,没有用(
    docker-compose.yml:
api:
    image: service-api
    build:
      context: "api/."
      dockerfile: "Dockerfile"
    environment:
      NODE_ENV: production
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/eshop
    networks:
      - backend
      - frontend
    depends_on:
      - 'mongo'
      - 'rabbitmq'
    ports:
      - "8802:8802"
    deploy:
      placement:
        constraints: [ node.role == manager ]
      replicas: 1
...

  mongo:
    image: mongo:6.0.2
    networks:
      - backend
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_DATABASE: eshop
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      - "/opt/mongo/data/db:/data/db"
    deploy:
      placement:
        constraints: [ node.role == manager ]
      replicas: 1

NestJS app.module.ts:

const MongoModule = MongooseModule.forRoot('mongodb://root:example@mongo:27017/eshop', {
  useNewUrlParser: true,
  useUnifiedTopology: true, 
  useFindAndModify: false,
});

Mongoose 版本:^5.8.11
错误信息:

[MongooseModule] Unable to connect to the database. Retrying (1)... +29999ms
[MongooseModule] Unable to connect to the database. Retrying (2)... +33002ms
...
[MongooseModule] Unable to connect to the database. Retrying (7)... +33002ms

所有东西都在同一个堆栈、同一个网络中工作,但仍然无法连接

xuo3flqw

xuo3flqw1#

authSource选项设置为admin

const MongoModule = MongooseModule.forRoot('mongodb://root:example@mongo:27017/eshop?authSource=admin', {
  useNewUrlParser: true,
  useUnifiedTopology: true, 
  useFindAndModify: false,
});

相关问题