Search code examples
mysql.netdockerubuntu

Can't access MySql database from my Docker container with .Net API


At the start I would like to say I'm new here and sorry if my question will be not precise.

Ubuntu 18.4 hosted on VPS, MySql-server installed (not Docker) on same system where I run Docker with API.

Can't access MySql database from my Docker container with .Net API.

Dockerfile:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

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 ["CVMakerAPI/CVMakerAPI.csproj", "CVMakerAPI/"]
RUN dotnet restore "CVMakerAPI/CVMakerAPI.csproj"
COPY . .
WORKDIR "/src/CVMakerAPI"
RUN dotnet build "CVMakerAPI.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "CVMakerAPI.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "CVMakerAPI.dll"]

In ConnecitonString I'm using user that have access to this DB

When I try to do some request I'm getting:

If more info needed please ask.


Solution

  • Inside container we are in a different network space. So by default we do not have access to anything running in the host network. In this case MySQL.

    By default all docker container uses the Bridge network mode. https://docs.docker.com/network/

    In terms of Docker, a bridge network uses a software bridge which allows containers connected to the same bridge network to communicate, while providing isolation from containers which are not connected to that bridge network. The Docker bridge driver automatically installs rules in the host machine so that containers on different bridge networks cannot communicate directly with each other.

    So your container can not talk to the Mysql running on the host network.

    To access the host network from container you can run you container in the host network namespace.

    docker run --network host <your container>
    

    https://docs.docker.com/network/host/