Search code examples
mongodbspring-bootdocker

Unable to connect to docker mongo db from spring


I am trying to connect to my docker mongo db. I have this docker-compose:

version: '3.8'

services:

  mongo:
    image: mongo
    container_name: mongodb
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

  mongo-express:
    image: mongo-express
    container_name: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example
      ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/
      ME_CONFIG_BASICAUTH: false

These are my properties:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=root
spring.data.mongodb.password=pass
spring.data.mongodb.repositories.enabled=true

I keep getting this error : Exception opening socket Connection refused: no further information.

I have tried @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class}) This does not throw errors. I have also tried different configurations for mongo, but I don't understand why mongo cannot connect.


Solution

  • To be able to reach the database container from the host, you need to map it's port to a host port.

    Mongo is listening on port 27017 and if you want to map it to port 27017 on the host (so it matches your Spring configuration), you add a ports section to your service definition, like this

    services:
    
      mongo:
        image: mongo
        container_name: mongodb
        restart: always
        ports:
          - 27017:27017
        environment:
          MONGO_INITDB_ROOT_USERNAME: root
          MONGO_INITDB_ROOT_PASSWORD: example
    

    Then you should be able to reach it from the host.