Spring boot + mongodb (in docker container)

background: the backend courses covered

  1. using h2 database (in-memory, relational database) -- only need to import the dependency in pom.xml.
  2. how to init mysql in docker container -- docker-compose up.

target: using mongodb with spring boot application.

Problem A

The first problem is the same as that of connecting docker-contained mysql, even though mongodb has been successfully initiated (see ).

Spring boot + mongodb (in docker container)_第1张图片
image.png

The problem is

  1. that the one cannot use localhost or 192.0.0.1 to access a container, nor can one use
  2. nor can one access a container with the container's ip.
  3. one MUST use the docker machine's IP to access the docker container.
    the detailed solution may refer to

Problem B

The second one is how to config the application.yml or application.properties under /resources directory. After some trial and error I found the following concise solution application.properties:

server.port=9001
spring.application.name=supply-location-service
spring.data.mongodb.uri=mongodb://192.168.99.100:27017/test

NOTE: a important experience is that:
error occurs if you don't explicitly assign the DATABASE NAME (here is test)

P.S. The docker-compose.yml

mongodb:
  image: mongo:3.4.4
  ports:
    - "27017:27017"

extra resources on writing application.properties: https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
e.g. the part that covers MongoDB

Spring boot + mongodb (in docker container)_第2张图片
image.png

Problem starting docker-quick-start terminal

The problem is similar to https://github.com/docker/toolbox/issues/317

Spring boot + mongodb (in docker container)_第3张图片
image.png

solution: 移除docker-machine,新建docker-machine.

I'd highly suggest removing the machine and starting over from scratch (make sure to use the latest version of Docker Machine). docker-machine rm -f default && docker-machine create -d virtualbox default
see https://github.com/docker/machine/issues/2740

Now it is fine:


Spring boot + mongodb (in docker container)_第4张图片
image.png

你可能感兴趣的:(Spring boot + mongodb (in docker container))