尝试在运行 ASP.NET Core API 的 Docker 容器中访问 Swagger 时遇到 ERR_EMPTY_RESPONSE 错误。 API 和 Docker 设置似乎是正确的,但我无法访问 Swagger。
当我尝试通过访问 http://localhost:5101/swagger 访问 Swagger UI 时,我的浏览器中收到 ERR_EMPTY_RESPONSE 错误。我已验证 API 和 Docker 容器正在运行,并且端口映射似乎正确。 API 本身似乎运行正常,因为我可以直接访问其他端点。
Docker 配置(docker-compose.yml):
`version: '3.4'
services:
catalog.api:
environment:
- ASPNETCORE_ENVIRONMENT=Development
ports:
- "5101:80"
- "9101:81"
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
sqldata:
environment:
- SA_PASSWORD=Pass@word
- ACCEPT_EULA=Y
ports:
- "5433:1433"
volumes:
- bond-sqldata:/var/opt/mssql
volumes:
bond-sqldata:
external: false`
ASP.NET Core 应用程序(launchSettings.json):
`{
"profiles": {
"Catalog.API": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5222/"
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"publishAllPorts": true
}
}
}`
ASP.NET Core API 的 Dockerfile:
`FROM mcr.microsoft.com/dotnet/aspnet:8.0-preview AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:8.0-preview AS build
WORKDIR /src
COPY ["Services/Catalog/Catalog.API/Catalog.API.csproj", "Services/Catalog/Catalog.API/"]
RUN dotnet restore "Services/Catalog/Catalog.API/Catalog.API.csproj"
COPY . .
WORKDIR "/src/Services/Catalog/Catalog.API"
RUN dotnet build "Catalog.API.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Catalog.API.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Catalog.API.dll"]`
UPD:在端口之后工作:
变成这样了。 但我想知道原因。
找到原因:
新行为 从 .NET 8 开始,如果映射到容器中的端口 80,而没有显式设置容器中使用的 ASP.NET Core 端口,则任何连接到该映射端口的尝试都将失败。
例如,如果运行以下命令,您将无法使用端口 9999 在本地连接到应用程序。
docker 运行 --rm -it -p 9999:80
相反,更改命令以在容器内使用端口 8080:
docker 运行 --rm -it -p 9999:8080