I have a Spring Boot Application and developed it with a mongo db which was running in brew services.
To get a connection to the db I just had to put the following
Try not defining the ports of Mongo.
version: '3'
services:
mongo:
container_name: docker-mongo
image: mongo:latest
volumes:
- ./data/db:/data/db
spring:
depends_on:
- mongo
image:
docker-spring-http-alpine
ports:
- "8080:8080"
links:
- mongo
EDIT:
I've never done spring-boot development, but the error you are saying is being displayed may very well be unrelated to the mongo issue. However, here is an explanation as to why your mongo-connection is failing:
docker-compose
creates a virtual network if one hasn't been specified in the file (like in your case).
All your applications run inside of this network, completely isolated from each other. As such, localhost
in your spring-boot container actually refers to itself. Meaning your spring-boot application is expecting the mongo
instance to be running inside of its container (which its not, it's in a different container).
This would have been fine when both the database and application was running on your laptop's network. But as mentioned, they are now running in the docker-compose
network, in complete isolation.
However, docker-compose
is really clever! It creates a DNS for each of your containers which uses the service-name (in your case mongo
and spring
) specified in your docker-compose
file to allow for easy access to the containers inside of the network.
So, you should be able to change spring.data.mongodb.uri=mongodb://localhost:27017/db
to spring.data.mongodb.uri=mongodb://mongo:27017/db
and that should allow it to connect.
Try the following docker-compose.yml
. hostname
should fix your problem
version: '3'
services:
mongo:
container_name: docker-mongo
image: mongo:latest
ports:
- "27017:27017"
volumes:
- ./data/db:/data/db
hostname: mongo
spring:
depends_on:
- mongo
image:docker-spring-http-alpine
ports:
- "8080:8080"
hostname: spring
links:
- mongo