I have an API in .NET 8 that is a Docker container running inside a virtual machine with the internal IPv4 address 1.1.1.1 (for example).
This API uses a MySQL 8.0.33 database, and this is my connection string:
"ConnectionStrings": {
"MySQL": "Server=1.1.1.1;Port=3306;initial catalog=db_namel;uid=my-user;pwd=my-pass"
}
When I run the API locally (by changing the “Server” field value to “localhost”), everything works fine. My problem occurs when I dockerize my API and run it inside my Linux server (Ubuntu 22.04).
This is my Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["Presentation.Web/Presentation.Web.csproj", "Presentation.Web/"]
RUN dotnet restore "Presentation.Web/Presentation.Web.csproj"
COPY . .
WORKDIR "/src/Presentation.Web"
RUN dotnet build "Presentation.Web.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Presentation.Web.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Presentation.Web.dll"]
As soon as I create the container for my API on my Ubuntu server, I get the following error:
An error occurred using the connection to database '' on server '1.1.1.1'.
Unhandled exception. System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call.
---> MySqlConnector.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
To try to solve the problem, I created a new my-user
through these commands:
CREATE USER 'my-user'@'localhost' IDENTIFIED BY 'my-user';
GRANT ALL PRIVILEGES ON *.* TO 'my-user'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
It is worth mentioning that inside my server (via SSH), I can connect to the database without any issues using the command
mysql -u my-user -p
.
Later, I deleted the my-user and tried creating it again with the server’s internal IP address:
CREATE USER 'my-user'@'1.1.1.1' IDENTIFIED BY 'my-user';
GRANT ALL PRIVILEGES ON *.* TO 'my-user'@'1.1.1.1' WITH GRANT OPTION;
FLUSH PRIVILEGES;
As you can imagine, that didn’t work either.
I researched the problem and believe it might have something to do with Docker networks, as according to this answer, “The docker network is for container-to-container communication only”. My question is: how can I make my container “see” my connection string correctly?