I'm trying to run a .NET API with MySQL as the database, using Entity Framework to set up the database (so from API -> MySQL migrations).
The API seems to run well, and I think MySQL is also running fine. However, when I try to make a request, the Docker console throws this error:
mysql-1 | 2024-10-30T03:02:44.680273Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.40' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
api-1 | fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
api-1 | Failed executing DbCommand (44ms) [Parameters=[@p0='?' (DbType = Int32), @p1='?' (Size = 4000), @p2='?' (Size = 4000), @p3='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
api-1 | SET AUTOCOMMIT = 1;
api-1 | INSERT INTO `User` (`Id`, `Email`, `Name`, `Password`)
api-1 | VALUES (@p0, @p1, @p2, @p3);
I will share the files down below. Let me know if I need to share something else to troubleshoot this issue.
Try files:
Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["ApiNetEFMySQL.csproj", "."]
RUN dotnet restore "./ApiNetEFMySQL.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./ApiNetEFMySQL.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./ApiNetEFMySQL.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ApiNetEFMySQL.dll"]
docker-compose (You can see the commands I'm giving to Entity Framework.):
services:
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
environment:
- ASPNETCORE_ENVIRONMENT=Production
- ConnectionStrings__LocalConnection=Server=mysql;Port=3306;Database=testapi;User ID=root;Password=2870FJlw;
depends_on:
- mysql
command: >
sh -c "until nc -z mysql 3306; do echo 'Waiting for MySQL...'; sleep 2; done; dotnet ef database update; dotnet ApiNetEFMySQL.dll"
networks:
- my_network
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: 2870FJlw
MYSQL_DATABASE: testapi
ports:
- "3307:3306"
volumes:
- mysql_data:/var/lib/mysql
networks:
- my_network
volumes:
mysql_data:
networks:
my_network:
The connection string:
"ConnectionStrings": {
"LocalConnection": "Server=mysql;Port=3307;Database=testapi;User ID=root;Password=<mypassword>;"
}
}
Just in case the Program.cs file config for connections:
var connection = builder.Configuration.GetConnectionString("LocalConnection") ??
throw new InvalidOperationException("String de conexion no encontrada.");
builder.Services.AddDbContext<UserContext>(options =>
options.UseMySql(
connection,
ServerVersion.AutoDetect(connection)));