You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot应用连接Docker-Compose部署的MongoDB时认证失败

解决Docker部署MongoDB的Spring Boot认证失败问题

先看你的配置:

docker-compose.yml

version: '4'
services:
  mongodb:
    image: mongo:7.0.5
    container_name: mongodb
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: product-service
    volumes:
      - ./data:/data/db

application.properties

spring.application.name=product-service
spring.data.mongodb.uri=mongodb://root:password@localhost:27017/product-service?authSource=admin

报错信息

com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}

解决步骤

  1. 清理残留数据卷
    你的配置挂载了本地./data目录到容器的/data/db,如果之前启动过未开启认证的MongoDB,数据卷里会残留无认证的数据库文件,导致新的认证配置不生效。执行以下操作:

    • 停止并移除容器:docker-compose down
    • 删除本地数据目录:rm -rf ./data(如果有重要数据请先备份)
    • 重新启动容器:docker-compose up -d
  2. 修正Docker Compose版本
    Docker Compose目前没有稳定的4版本,最高稳定版为3.x(推荐使用3.8),版本不兼容可能导致环境变量未正确加载。把version: '4'改为version: '3.8'。

  3. 验证MongoDB用户配置
    进入容器验证root用户是否正确创建:

    • 执行命令:docker exec -it mongodb mongosh -u root -p password --authenticationDatabase admin
    • 若能成功进入Mongo Shell,说明用户配置没问题;若失败,检查环境变量是否正确,重新执行步骤1。
  4. 确认连接字符串正确性
    你的连接字符串已经指定了authSource=admin(root用户属于admin库),这是正确的配置。如果你的Spring Boot应用也运行在Docker容器中,需要把localhost替换为容器名mongodb(同一Docker网络下),但如果应用是本地运行,localhost没问题。

完成以上步骤后重新启动Spring Boot应用,应该能正常连接MongoDB。

内容的提问来源于stack exchange,提问作者M Hari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:33:17