简体   繁体   中英

How to connect to specific local MongoDB instance in Spring Boot Dockerised application?

I have developed simple Spring Boot Application that performs CRUD operations using MongoDB as database. I have deployed that application in Docker but I get null values while doing GET Request for any items stored in MongoDB. Some of the files required for Docker are provided below:

Dockerfile:

  VOLUME /tmp
  ADD build/libs/Spring-Boot-MongoDB-0.0.1-SNAPSHOT.jar SpringMongoApp.jar
  ENTRYPOINT ["java", "-Dspring.data.mongodb.uri=mongodb://mongo:27018/otp","-jar","/SpringMongoApp.jar"]

docker-compose.yml:

version: "3"
services:
  api-database:
    image: mongo:3.2.4
    container_name: "springboot-mongo-app"
    ports:
      - "27018:27017"
    environment:
      MONGO_INITDB_ROOT_DATABASE: otp
    networks:
      - test-network

  api:
    image: springboot-api
    ports:
      - "8080:8080"
    depends_on:
      - api-database
    networks:
      - test-network

networks:
  test-network:
    driver: bridge

application.properties:

spring.data.mongodb.host=api-database

When I checked the MongoDb Docker container using container ID, it is automatically getting connected to test database but not to otp database which I have mentioned in environment section of docker-compose.yml file.

The problem is that your docker container is not persistent, the database will be erased and re-created again each time you run your docker container.

If you add VOLUME to persist /data/db , you will get desired result.

I assume your have directory data/db in the same place where you have stored docker-compose.yml . You may setup custom directory (ie /tmp/data/db )

Try this one:

docker-compose.yml:

version: "3"
services:
  api-database:
    image: mongo:3.2.4
    container_name: "springboot-mongo-app"
    ports:
      - "27018:27017"
    volumes:
      - "./data/db:/data/db"
    environment:
      MONGO_INITDB_ROOT_DATABASE: otp
    networks:
      - test-network

  api:
    image: springboot-api
    ports:
      - "8080:8080"
    depends_on:
      - api-database
    networks:
      - test-network

networks:
  test-network:
    driver: bridge

Note: First time, it will be empty database. If you create collections, insert records, etc... it will be saved in ./data/db

我想,而不是MONGO_INITDB_ROOT_DATABASE你应该使用MONGO_INITDB_DATABASE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM