SpringBoot and MongoDb integration in the Docker - mongodb

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

version: '3'
services:
db:
image: postgres
environment:
POSTGRES_PASSWORD: password
mongodb:
image: mongo
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: password
You can find above configuration of docker file that includes both MongoDB and PostgreSQL configurations.

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
mongodb:
build:
context: mongodb
args:
DOCKER_ARTIFACTORY: ${DOCKER_ARTIFACTORY}
container_name: mongodb
hostname: mongodb
restart: always
environment:
- MONGO_INITDB_DATABASE=databaseName
- MONGO_INITDB_ROOT_USERNAME=username
- MONGO_INITDB_ROOT_PASSWORD=password
ports:
- 27017:27017
volumes:
- /mongodata:/data/mongodb
networks:
- somenetwork
created below file (filename: mongodbsetup.sh) under projectFolder/builder/mongodb/init
#!/bin/bash
mongosh <<EOF
use code
EOF
created below file (filename: Dockerfile) under projectFolder/builder/mongodb
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"]
In application.properties file added below properties
#MongoDB configurations
spring.data.mongodb.database=databasename
spring.data.mongodb.uri=mongodb://username:password#databaseurlOrIpAddress:27017
That's it. It's working.

Related

MongoDb : Cannot connect database on Docker container

I use the following docker-compose.yml to build a MongoDb database in a Docker container:
version: "3"
services:
mongodb:
image: mongo:latest
container_name: mongodb
volumes:
- mongo_data:/data/db
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: pass
MONGODB_USERNAME: user
MONGODB_PASSWORD: pass
MONGO_INITDB_DATABASE: social-network-db
volumes:
mongo_data:
Then I restarted the container and try to connect database via MongoDb Compass app by using these values:
Connection parameters
So, what is wrong and why I cannot connect to my MongoDb database? If you have some suggestion regarding to adocker-compose.yml parameter or creating used while building container, please inform me.

docker-entrypoint-initdb.d not executing scripts

I'm using docker-compose version 1.25.5, build 8a1c60f6 &
Docker version 19.03.8, build afacb8b
I'm trying to initialise database with Users in MongoDb container using docker-entrypoint-initdb.d but,
js/scripts aren't being executed when container starts.
I know /data/db must be empty for it execute so I've been deleting it every time before start. But still doesn't execute. Going into the container and manually executing mongo mongo-init.js works.
Not sure why it's not working when it should.
docker-compose.yml:
version: '3'
services:
mongodb:
container_name: "mongodb"
image: tonyh308/cv-mongodb:1
build: ./mongo
container_name: mongodb
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_DATABASE: test
volumes:
- ./docker-entrypoint-initdb.d/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
- ./mongo/mongodb:/data/db
labels:
com.qa.description: "MongoDb Container for application."
# other services ...
Dockerfile:
FROM mongo:3.6.18-xenial
RUN apt-get update
COPY ./Customers /Customers
COPY ./test /test
WORKDIR /data
ENTRYPOINT ["mongod", "--bind_ip_all"]
EXPOSE 27017
Feb 26 2021: still no solution

Data does not persist to host volume with docker-compose.yml for MongoDB

Have docker installed on my Mac along with MongoDB image. When I start the container with volume specified directly in the docker run command, the data gets persisted even after I stop the container. But the same does not work when I do it via docker-compose.yml. Can someone suggest what's wrong with the docker-compose.yml file?
When I do this, the data gets persisted:
docker run --name mongodb -v /Users/shrap7/projects/mongodb/data:/data/db --rm -d mongo
But when I try the same with docker-compose.yml - it does not persist data.
version: '3.4'
services:
mongodb:
image: mongo:latest
container_name: "mongodb"
volumes:
- /Users/shrap7/projects/mongodb/data:/data/db
ports:
- 27017:27017
I tried with double quotes, tried relative path, i.e. ./data:/data/db, but no luck. Thank you.
I'm using Windows and I had the same issue today. I found this gist that shows a mongodb configuration for docker-compose, and it has support for named volumes. I tried using named volumes and it worked for me.
So in your case, you could try the following configuration (with named volumes):
services:
mongodb:
image: mongo:latest
container_name: "mongodb"
volumes:
- mongodb:/data/db
- mongodb_config:/data/configdb
ports:
- 27017:27017
volumes:
mongodb:
mongodb_config:

How do I properly set up my Keystone.js app to run in docker with mongo?

I have built my app which runs fine locally. When I try to run it in docker (docker-compose up) it appears to start, but then throws an error message:
Creating mongodb ... done
Creating webcms ... done
Attaching to mongodb, webcms
...
Mongoose connection "error" event fired with:
MongoError: failed to connect to server [localhost:27017] on first connect
...
webcms exited with code 1
I have read that with Keystone.js you need to configure the Mongo location in the .env file, which I have:
MONGO_URI=mongodb://localhost:27017
Here is my Docker file:
# Use node 9.4.0
FROM node:9.4.0
# Copy source code
COPY . /app
# Change working directory
WORKDIR /app
# Install dependencies
RUN npm install
# Expose API port to the outside
EXPOSE 3000
# Launch application
CMD ["node","keystone"]
...and my docker-compose
version: "2"
services:
# NodeJS app
web:
container_name: webcms
build: .
ports:
- 3000:3000
depends_on:
- mongo
# MongoDB
mongo:
container_name: mongo
image: mongo
volumes:
- ./data:/data/db/mongo
ports:
- 27017:27017
When I run docker ps it confirms that mongo is up and running in a container...
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f3e06e4a5cfe mongo "docker-entrypoint.s…" 2 hours ago Up 2 hours 0.0.0.0:27017->27017/tcp mongodb
I am either missing some config or I have it configured incorrectly. Could someone tell me what that is?
Any help would be appreciated.
Thanks!
It is not working properly because you are sending the wrong host.
your container does not understand what is localhost:27017 since it's your computer address and not its container address.
Important to understand that each service has it's own container with a different IP.
The beauty of the docker-compose that you do not need to know your container address! enough to know your service name:
version: "2"
volumes:
db-data:
driver: local
services:
web:
build: .
ports:
- 3000:3000
depends_on:
- mongo
environment:
- MONGO_URI=mongodb://mongo:27017
mongo:
image: mongo
volumes:
- "db-data:/data/db/mongo"
ports:
- 27017:27017
just run docker-compose up and you are all-set
A couple of things that may help:
First. I am not sure what your error logs look like but buried in my error logs was:
...Error: The cookieSecret config option is required when running Keystone in a production environment.Update your app or environment config so this value is supplied to the Keystone constructor....
To solve this problem, in your Keystone entry file (eg: index.js) make sure your Keystone constructor has the cookieSecret parameter set correctly: process.env.NODE_ENV === 'production'
Next. Change the mongo uri from the one Keystone generated (mongoUri: mongodb://localhost/my-keystone) to: mongoUri: 'mongodb://mongo:27017'. Docker needs this because it is the mongo container address. This change should also be reflected in your docker-compose file under the environment variable under MONGO_URI:
... environment: - MONGO_URI=mongodb://mongo:27017 ...
After these changes your Keystone constructor should look like this:
const keystone = new Keystone({
adapter: new Adapter(adapterConfig),
cookieSecret: process.env.NODE_ENV === 'production',
sessionStore: new MongoStore({ url: 'mongodb://mongo:27017' }),
});
And your docker-compose file, something like this (I used a network instead of links for my docker-compose as Docker has stated that links are a legacy option. I've included mine in case its useful for anyone else):
version: "3.3"
services:
mongo:
image: mongo
networks:
- appNetwork
ports:
- "27017:27017"
environment:
- MONGO_URI=mongodb://mongo:27017
appservice:
build:
context: ./my-app
dockerfile: Dockerfile
networks:
- appNetwork
ports:
- "3000:3000"
networks:
appNetwork:
external: false
It is better to use mongo db atlas if you does not want complications. You can use it in local and in deployment.
Simple steps to get the mongo url is available in https://www.mongodb.com/cloud/atlas
Then add a env variable
CONNECT_TO=mongodb://your_url
For passing the .env to docker, use
docker run --publish 8000:3000 --env-file .env --detach --name kb keystoneblog:1.0

Trying to connect a NodeJS app to MongoDB via Docker Compose

I'm following a MongoDB + NodeJS tutorial with my app. Everything works without Docker.. and I can in fact get the app to work up until it needs to connect to MongoDB.
If my app doesn't see MongoDB, it will print out an error and halt.
Here's my files
.env
NODE_VIEWS_PATH=../
NODE_PUBLIC_PATH=../
MONGODB_URI='mongodb://127.0.0.1:27017/myappsdb'
...
Dockerfile
FROM node:carbon
# Create app directory
WORKDIR /usr/src/mahrio
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm install --only=production
COPY . .
EXPOSE 6085
CMD ["npm", "start"]
docker-compose.yml
version: "2"
services:
app:
container_name: someappname
restart: always
build: .
ports:
- "6085:6085"
links:
- mongo
depends_on:
- mongo
mongo:
container_name: mongo
image: mongo
volumes:
- ./tmp:/data/db
ports:
- "27017:27017"
When using docker-compose, for a container to connect to another container it can use the service name as a hostname to connect.
In your case, the node app needs to connect to mongo:27017 rather than localhost:27017, since localhost from the respective of the app container will refer to itself and not to your machine.
Therefore, change the mongo url to MONGODB_URI='mongodb://mongo:27017/myappsdb'. Also make sure that you consume the env file by adding:
app:
...
env_file:
- file.env