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

huangapple go评论73阅读模式
英文:

ASP.Net Core can't connect to MySql database in docker

问题

I have error in the fifth line when asp.net try to connect db.
我在第五行遇到了错误,当 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()

I have an asp.net core project and two databases. I am creating a docker compose file.
我有一个 asp.net core 项目和两个数据库。我正在创建一个 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"

I am using generated file docker
我正在使用生成的 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

<details>
<summary>英文:</summary>

I have error in the fifth line when asp.net try to connect db.

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, Nullable1 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_02.&lt;Execute&gt;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, Func3 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, Func3 verifySucceeded)
2023-06-02 09:37:00 at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func
2 operation, Func2 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()


I have an asp.net core project and two databases. I am creating a docker compose file.

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"

I am using generated file 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"]



In programm.cs i have:

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

and

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



In appsettings.json i have:

"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"
},


I run 
`docker-compose up -d` in cmd. And i have this result [Created container](https://i.stack.imgur.com/ms4HP.png) but asp won&#39;t start.

I try edit appsettings.json to:

&quot;ClothingShopConnection&quot;: &quot;server=localhost;port=3306;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1&quot;,
&quot;IdentityConnection&quot;: &quot;server=localhost;port=3306;user=root;password=root;database=identity&quot;

&quot;ClothingShopConnection&quot;: &quot;server=localhost;port=3307;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1&quot;,
&quot;IdentityConnection&quot;: &quot;server=localhost;port=3308;user=root;password=root;database=identity&quot;

&quot;ClothingShopConnection&quot;: &quot;server=db-1;port=3307;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1&quot;,
&quot;IdentityConnection&quot;: &quot;server=db-2;port=3308;user=root;password=root;database=identity&quot;
but to no avail.

An interesting fact is that it mysql worckbanch connector sees these databases and makes it possible to connect to them through localhost: 3307 and 08, respectively.[Successful connection](https://i.stack.imgur.com/lFNOi.png). Db created correct.

I&#39;ve looked at similar threads but haven&#39;t found an answer.


</details>


# 答案1
**得分**: 1

我通过以下方式配置连接字符串来解决了我的问题:

"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 提出的出色问题。

<details>
<summary>英文:</summary>

I solved my problem by configuring the connection string like this:

    &quot;ConnectionStrings&quot;: {
    &quot;ClothingShopConnection&quot;: &quot;server=dbClothingShop;port=3306;user=root;password=root;Pooling=true;Max Pool Size=200;database=clothingshop1&quot;,
    &quot;IdentityConnection&quot;: &quot;server=dbIdentity;port=3306;user=root;password=root;database=identity&quot;
    }
And apparently part of the problem was due to incorrect reading of tables from the database. Tables with capital letters were expected, but in the table they are with small letters (apparently something broke when importing and exporting the database).
I solved it with attributes DataAnnotation:

    
    [Table(&quot;size&quot;)]
    public class Size
    {
       //SizeID...
    }

Thanks a lot for the great questions @QiangFu

</details>



huangapple
  • 本文由 发表于 2023年6月2日 14:01:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定