ASP.Net Core无法连接到Docker中的MySql数据库

oyjwcjzk  于 12个月前  发布在  Mysql
关注(0)|答案(1)|浏览(172)

当www.example.com尝试连接数据库时,第五行出现错误asp.net。

2023-06-02 09:36:59 warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
2023-06-02 09:36:59       Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
2023-06-02 09:37:00 info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
2023-06-02 09:37:00       Entity Framework Core 6.0.8 initialized 'AppIdentityDbContext' using provider 'Pomelo.EntityFrameworkCore.MySql:6.0.2' with options: ServerVersion 0.0-mysql 
2023-06-02 09:37:00 fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
2023-06-02 09:37:00       An error occurred using the connection to database '' on server 'db2'.
2023-06-02 09:37:00 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.
2023-06-02 09:37:00  ---> MySqlConnector.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.
2023-06-02 09:37:00    at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, MySqlConnection connection, Int32 startTickCount, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/Core/ServerSession.cs:line 433
2023-06-02 09:37:00    at MySqlConnector.MySqlConnection.CreateSessionAsync(ConnectionPool pool, Int32 startTickCount, Nullable`1 ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlConnection.cs:line 926
2023-06-02 09:37:00    at MySqlConnector.MySqlConnection.OpenAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlConnection.cs:line 406
2023-06-02 09:37:00    at MySqlConnector.MySqlConnection.Open() in /_/src/MySqlConnector/MySqlConnection.cs:line 369
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
2023-06-02 09:37:00    at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlRelationalConnection.Open(Boolean errorsExpected)
2023-06-02 09:37:00    at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
2023-06-02 09:37:00    at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
2023-06-02 09:37:00    --- End of inner exception stack trace ---
2023-06-02 09:37:00    at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
2023-06-02 09:37:00    at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.Exists(Boolean retryOnNotExists)
2023-06-02 09:37:00    at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.Exists()
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.GetAppliedMigrations()
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetAppliedMigrations(DatabaseFacade databaseFacade)
2023-06-02 09:37:00    at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetPendingMigrations(DatabaseFacade databaseFacade)
2023-06-02 09:37:00    at ClothingShop.Models.IdentitySeedData.EnsurePopulated(IApplicationBuilder app) in /src/Models/IdentitySeedData.cs:line 16
2023-06-02 09:37:00    at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_1(Object state)
2023-06-02 09:37:00    at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
2023-06-02 09:37:00    at System.Threading.ThreadPoolWorkQueue.Dispatch()
2023-06-02 09:37:00    at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
2023-06-02 09:37:00    at System.Threading.Thread.StartCallback()

我有一个asp.net核心项目和两个数据库。我正在创建一个docker compose文件。

version: '3.8'

services:
  web:
    build: .
    ports:
      - "8000:80"
    depends_on:
      - db1
      - db2

  db1:
    image: mysql:8.0.30
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: clothingshop1
    volumes:
      - ./db1:/docker-entrypoint-initdb.d
    ports:
      - "3307:3306"

  db2:
    image: mysql:8.0.30
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: identity
    volumes:
      - ./db2:/docker-entrypoint-initdb.d
    ports:
      - "3308:3306"

我正在使用生成的文件docker

#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["ClothingShop.csproj", "."]
RUN dotnet restore "./ClothingShop.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "ClothingShop.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "ClothingShop.csproj" -c Release -o /app/publish /p:UseAppHost=false

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

在programm.cs中,我有:

builder.Services.AddDbContext<StoreDbContext>(opts =>
{
    opts.UseMySql(builder.Configuration.GetConnectionString("ClothingShopConnection"), new MySqlServerVersion(new Version()), b => b.EnableRetryOnFailure());
});

和/或

builder.Services.AddDbContext<AppIdentityDbContext>(options =>
 options.UseMySql(builder.Configuration.GetConnectionString("IdentityConnection"), new MySqlServerVersion(new Version())));

在appsettings.json中,我有:

"AllowedHosts": "*",
  "ConnectionStrings": {
    "ClothingShopConnection": "server=db1;port=3307;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1",
    "IdentityConnection": "server=db2;port=3308;user=root;password=root;database=identity"
  },

我在cmd中运行docker-compose up -d。我有这个结果Created container,但asp不会启动。
我尝试编辑appsettings.json以:

"ClothingShopConnection": "server=localhost;port=3306;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1",
    "IdentityConnection": "server=localhost;port=3306;user=root;password=root;database=identity"
"ClothingShopConnection": "server=localhost;port=3307;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1",
    "IdentityConnection": "server=localhost;port=3308;user=root;password=root;database=identity"
"ClothingShopConnection": "server=db-1;port=3307;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1",
    "IdentityConnection": "server=db-2;port=3308;user=root;password=root;database=identity"

但无济于事。
一个有趣的事实是,mysql worckbanch连接器可以看到这些数据库,并可以通过localhost连接到它们:3307和08。Successful connection. Db创建正确。
我看过类似的帖子,但没有找到答案。

n8ghc7c1

n8ghc7c11#

我通过如下配置连接字符串解决了这个问题:

"ConnectionStrings": {
"ClothingShopConnection": "server=dbClothingShop;port=3306;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1",
"IdentityConnection": "server=dbIdentity;port=3306;user=root;password=root;database=identity"
}

显然,部分问题是由于从数据库中错误地阅读表。表中的大写字母是预期的,但在表中,它们是小写字母(显然是在导入和导出数据库时出现了问题)。我用属性DataAnnotation解决了这个问题:

[Table("size")]
public class Size
{
   //SizeID...
}

非常感谢@QiangFu的精彩提问

相关问题