'Docker - Mongo DB instance not connecting with application
I am using docker mongo with my aspnet core application but I am unable to make connection with mongodb which is running under container. Although I am able to connect MongoDB compass GUI with MongoDB running under docker But my application is not connecting. Here are my steps
First I pull Mongo DB Image
docker pull mongo:latest
Then I create network bridge for mongo
docker network create --driver bridge mongo_db
Then I run mongo image with bridge network
docker run -d -p 27017:27017 --net=mongo_db --name mongodb mongo
after above steps I created my aspnetcore image file
docker build -t lmsapp/v2 .
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /app
EXPOSE 5000
EXPOSE 5001
COPY ["SharedKernal/SharedKernal.csproj", "SharedKernal/"]
COPY ["LMS.Entities/LMS.Entities.csproj", "LMS.Entities/"]
COPY ["LMS.Core/LMS.Core.csproj", "LMS.Core/"]
COPY ["LMS.Infrastructure/LMS.Infrastructure.csproj", "LMS.Infrastructure/"]
COPY ["LMS.Web/LMS.Web.csproj", "LMS.Web/"]
RUN dotnet restore "LMS.Web/LMS.Web.csproj"
COPY . .
WORKDIR "/app/LMS.Web"
CMD [ "/bin/bash","-c","dotnet restore && dotnet watch run" ]
and in the last step I run my custom image using the following command
docker run -d --net=mongo_db --name lms -p 5000:5000 -p 5001:5001 -v "$(pwd):/app".ToLower() -w "/app/LMS.Web" lmsapp/v2
Now when I browse the application I am unable to connect with mongo. Here is my connectionstring
"ConnectionString": "mongodb://localhost:27017"
I tried different verion of connection string but none is working except one
"ConnectionString": "mongodb://0.0.0.0:27017"
"ConnectionString": "mongodb://127.0.0.1:27017"
"ConnectionString": "mongodb://api:27017"
When I find the container IP and try to connect mongo with my application only then it works
"ConnectionString": "mongodb://172.1.8.1:27017"
But I am able to successfully connect my MongoDB compass GUI with mongo instance running in container.
Whats the issue behind all this?
Solution 1:[1]
Your connection string should be mongodb://CONTAINER_NAME
, so mongodb://mongo
in your case.
Here is a command that will work with your setup, and start a mongo client, just to demonstrate the point:
$ docker run --rm -it --net=mongo_db mongo mongo "mongodb://mongodb"
You can make life easier for you if you work with docker compose. Here is a working sample:
volumes:
mongodb:
services:
mongo:
image: mongo
ports: ["27017:27017"] # only needed if you need access from the host
volumes:
- mongodb:/data/db
client:
image: mongo
depends_on: [mongo]
entrypoint: mongo
command: mongodb://mongo
Run with:
$ docker-compose up -d mongo
$ docker-compose run client
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |