I have a SpringBoot application running in the docker and I am using PostgreSQL as a database for this project and the database also running in the docker.
Now, I want to use MongoDb along with PostgreSQL as database to my SpringBoot application.
I added MongoDb info in the docker-compose.yml file and created new Dockerfile and ran the application. After that MongoDb got installed and running in the docker successfully.
I created a api for insertion of a document into the collection. When I hit the api I am getting the error. I think, I am not able to connect to the MongoDb which is running in the docker.
error:- com.mongodb.MongoSocketOpenException: Exception opening socket
I think I have to do configuration in the MongoDb before doing any CRUD operations.
Can anyone please share a detailed configuration of MongoDb with some examples.
Or provide some information which can help me achieve my task.
Thanks.
Docker-compose.yml
mongodb:
build:
context: mongodb
args:
DOCKER_ARTIFACTORY: ${DOCKER_ARTIFACTORY}
container_name: “mongodb”
image: mongo:6.0.4
restart: always
environment:
- MONGODB_USER=${SPRING_DATASOURCE_USERNAME:-username}
- MONGODB_PASSWORD=${SPRING_DATASOURCE_PASSWORD:-password}
ports:
- “27017:27017”
volumes:
- “/mongodata:/data/mongodb”
networks:
- somenetwork
Dockerfile
ARG DOCKER_ARTIFACTORY
FROM ${DOCKER_ARTIFACTORY}mongo:6.0.4
COPY init/mongodbsetup.sh /docker-entrypoint-initdb.d/
RUN chmod +x /docker-entrypoint-initdb.d/mongodbsetup.sh
CMD [“mongod”]
2
Answers
I resolve the issue and successfully able to connect and able to perform CRUD operations too.
Below are the changes I did.
1. docker-compose.yml
created below file (filename: mongodbsetup.sh) under projectFolder/builder/mongodb/init
created below file (filename: Dockerfile) under projectFolder/builder/mongodb
In application.properties file added below properties
That's it. It's working.
You can find above configuration of docker file that includes both MongoDB and PostgreSQL configurations.