经过两天的绞尽脑汁和用头敲击键盘,我找到了解决方案。
首先,在我的appSettings文件中,我需要添加一个设置来测试与master数据库的连接,然后再连接到应用程序的数据库。这是因为最初并没有应用程序数据库,它只能通过运行数据库来创建。迁移()。
这是我的appSettings.json
{
"ConnectionStrings": {
"TestConnection": "Server=accsolsqlserver;Database=master;User Id=sa;Password=P@ssw0rd123;TrustServerCertificate=True;", //additional setting
"DefaultConnection": "Server=accsolsqlserver;Database=aspnet-AccSol-4e738ad6-a4fd-4a62-8afa-6641a1ee333c;User Id=sa;Password=P@ssw0rd123;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"APIBaseURL": "https://localhost:7040/",
"HstsOptions": {
"IncludeSubDomains": true,
"Preload": true,
"MaxAge": 31536000
},
"Kestrel": {
"Certificates": {
"Development": {
"CertsPath": "./certs/AccSol.pfx",
"Password": "P@ssw0rd123"
}
}
}
}
其次,我在Program.cs中为证书添加了代码。
var config = builder.Configuration.GetSection("Kestrel:Certificates:Development");
string certsPath = config.GetSection("CertsPath").Value ?? string.Empty;
string password = config.GetSection("Password").Value ?? string.Empty;
builder.WebHost.UseUrls(_baseAPIUrl);
builder.WebHost.ConfigureKestrel(options =>
{
//TODO: sol: these ports need to be in the appSettings file
options.Listen(IPAddress.Loopback, 5049); // HTTP
options.Listen(IPAddress.Loopback, 7040, listenOptions =>
{
listenOptions.UseHttps(certsPath, password);
});
});
第三,我确保Dockerfile中的这些环境变量位于最后一层,包括端口和证书路径。
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
COPY --from=build /src/AccSol.API/certs /certs
ENV ASPNETCORE_ENVIRONMENT=DockerSql
ENV ASPNETCORE_URLS=http://+:5049;https://+:7040
ENV ASPNETCORE_Kestrel__Certificates__Default__Password=P@ssw0rd123
ENV ASPNETCORE_Kestrel__Certificates__Default__Path=/certs/AccSol.pfx
EXPOSE 5049
EXPOSE 7040
ENTRYPOINT ["dotnet", "AccSol.API.dll"]
第四,我检查了docker-compose.yml文件中是否也声明了端口。我在某个地方读到没有必要这样做,但我仍然需要它,因为如果没有,它将在Docker Desktop中创建新的端口。
accsol.api:
image: ${DOCKER_REGISTRY-}accsolapi
volumes:
- "./AccSol.EF/Data:/scripts"
- "./certs:/certs"
build:
context: .
dockerfile: AccSol.API/Dockerfile
container_name: accsol.api
hostname: accsol.api
user: root
ports:
- "5049:5049"
- "7040:7040"
depends_on:
- sql
environment:
- ASPNETCORE_ENVIRONMENT=DockerSql
- ASPNETCORE_URLS=http://+:5049;https://+:7040
- ASPNETCORE_Kestrel__Certificates__Default__Password=P@ssw0rd123
- ASPNETCORE_Kestrel__Certificates__Default__Path=/certs/AccSol.pfx
- PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/mssql-tools/bin
networks:
accsolnet:
之后,api容器(accsol.api)能够连接到sql服务器容器(accsolsqlserver),它通过运行我的CreateInitialData.sql文件自动在数据库中创建初始数据。
所以这个问题现在已经解决了,但另一个问题出现了。
当我运行dockerrun时,我能够浏览api swagger页面并运行这些方法,没有任何问题。使用docker compose,我得到了ERR_CONNECTION_CLOSED。这是另一个问题,我已经在Docker社区论坛上创建了一个关于这个问题的帖子。
Here is the link to that post
.