SpringBoot and MongoDb connection in Docker

Hi All,

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 created the docker-compose.yml file and 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 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.

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”]

Hi @Aslam_Shaik and welcome to the MongoDB community forum!!

The following error is typically observed when the database is not running in the same container as the application.
Can you help me with the following information which would help me to provide the solution further:

  1. Is the application and the MongoDB running inside the same containers?
  2. Can you share the application.yaml/docker-compose.yaml file for the spring application.

Regards
Aasawari