Reputation: 131
I developed a simple dotnet core api that connects to mongo docker image. The application works perfectly with the following uri (mongodb://localhost:27017) : mongo connection string
{
"MongoDB": {
"Database": "messagesdb",
"Host": "localhost",
"Port": 27017,
"User": "",
"Password": ""
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
the JSON response Json Response after a successful run
But When I add a docker file via visual studio, and setting the host in the settings.json file to mongo instead of localhost, as the picture shows (mongodb://mongo:27017): mongo connection string
The Docker file :
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["ErrorMessagesAPI.csproj", ""]
RUN dotnet restore "./ErrorMessagesAPI.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "ErrorMessagesAPI.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "ErrorMessagesAPI.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ErrorMessagesAPI.dll"]
The docker-compose for mongo :
version: '3.8'
services:
mongo:
image: mongo
container_name: mongo
restart: always
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db
mongo-express:
image: mongo-express
container_name: mongo-express
restart: always
ports:
- "8081:8081"
depends_on:
- mongo
volumes:
mongo-data:
driver: local
The API doesn't work as the following picture depicts: docker run result, and the complete code can be found here MessageAPI
I am following the article found here Docker + MongoDB + .NET Core = a good tim Can anyone help with this?
Upvotes: 0
Views: 1497
Reputation: 131
I want to share my solution for this problem, so you can benefit from your turn. to link to the mongo image, you should update the docker-compose file, and leave the settings as-is. providing an environmental variable in the docker-compose will re-write the settings in the settings.json file, as the following:
version: '3.1'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
depends_on:
- mongo
todo-server:
build: .
restart: always
ports:
- 5000:80
environment:
MongoDB__Host: mongo
depends_on:
- mongo
Upvotes: 2