蒙戈快报|无法使用connectionString连接到数据库:mongodb:127.0.0.1:27017/“

vmdwslir  于 2023-10-16  发布在  Go
关注(0)|答案(2)|浏览(165)

当尝试使用docker-compose启动一个docker容器时,我得到以下错误消息:

(node:8) [MONGODB DRIVER] Warning: Current Server Discovery 

and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
mongo-express    | Could not connect to database using connectionString: mongodb://127.0.0.1:27017/"

我注意到mongo-express总是在我的连接字符串末尾添加一个双引号,这是故意的还是我在docker-compose文件中搞砸了?
文件:

version: '3.8'
services:
    mongodb:
        image: mongo:latest
        container_name: mongodb
        restart: unless-stopped
        networks:
            - backbone
        expose:
            - 27017
        ports:
            - 27017:27017
        env_file:
            - ./.env
        command: [--auth]
        environment:
            - MONGO_INITDB_ROOT_USERNAME=${DB_USERNAME}
            - MONGO_INITDB_ROOT_PASSWORD=${DB_PASSWORD}
        volumes:
            - ./data:/data/db

    mongo-express:
        image: mongo-express
        container_name: mongo-express
        restart: unless-stopped
        networks:
            - backbone
        ports:
            - 8081:8081
        environment:
            - ME_CONFIG_MONGODB_SERVER=127.0.0.1
            - ME_CONFIG_MONGODB_URL="mongodb://127.0.0.1:27017"
            - ME_CONFIG_BASICAUTH_USERNAME=${DB_USERNAME}
            - ME_CONFIG_BASICAUTH_PASSWORD=${DB_PASSWORD}

networks:
    backbone:
        driver: bridge

我已经尝试过更新我的docker/docker-compose和mongodb版本。
如何解决错误?或者有没有一个我可以使用的变通方法?

vu8f3i0k

vu8f3i0k1#

在容器中,localhost是指容器本身。因此,当Mongo Express尝试连接到localhost上的数据库时,它会在Mongo Express容器中查找数据库。
Docker compose允许你使用容器名来引用容器,所以你应该把你的Mongo Express环境变量改为

- ME_CONFIG_MONGODB_SERVER=mongodb
    - ME_CONFIG_MONGODB_URL="mongodb://mongodb:27017"
zhte4eai

zhte4eai2#

我在Hans Kilian的帮助下解决了这个问题,但我必须添加一个环境变量,这是我的docker-compose文件。

version: '3.3'

services:
  mongo:
    image: mongo:4.4
    container_name: mongodb
    environment:
      MONGO_INITDB_ROOT_USERNAME: root   # Root username access: Yes i sure.
      MONGO_INITDB_ROOT_PASSWORD: 123456 # Root password now required: Yes i will try this password.
    ports:
      - 27017:27017
    volumes:
      - ./mongo_data:/data/db

  mongo-express:
    image: mongo-express
    container_name: mongodb_web_client
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ENABLE_ADMIN: true # (WAIT) Access as root: Yes like the other container.
      ME_CONFIG_MONGODB_ADMINUSERNAME: root # Root username: Like the previous
      ME_CONFIG_MONGODB_ADMINPASSWORD: 123456 # Root password: Like the previous
      ME_CONFIG_MONGODB_SERVER: mongodb
      ME_CONFIG_MONGODB_URL: mongodb://mongodb:27017/
    depends_on:
      - mongo

相关问题