要解决"Asp.Net Core docker-compose https 自签名证书问题",你可以按照以下步骤进行操作:
生成自签名证书:
openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost" -keyout localhost.key -out localhost.crt
创建 Dockerfile 文件:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore "YourProject.csproj"
RUN dotnet build "YourProject.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "YourProject.csproj" -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS final
WORKDIR /app
COPY --from=publish /app/publish .
COPY localhost.crt /usr/local/share/ca-certificates/
RUN update-ca-certificates
ENV ASPNETCORE_URLS=https://+:443
ENV ASPNETCORE_Kestrel__Certificates__Default__Path=/app/localhost.crt
ENV ASPNETCORE_Kestrel__Certificates__Default__Password=
ENTRYPOINT ["dotnet", "YourProject.dll"]
创建 docker-compose.yml 文件:
version: '3.8'
services:
your_project:
build:
context: .
dockerfile: Dockerfile
ports:
- "443:443"
在你的项目代码中,确保将 UseHttpsRedirection()
和 UseHsts()
方法添加到 Configure
方法中:
app.UseHttpsRedirection();
app.UseHsts();
在运行 docker-compose up
命令之前,确保已在项目根目录下放置了生成的 localhost.crt
文件。
运行 docker-compose up
命令以启动项目,并在浏览器中访问 https://localhost
,应该能够看到已启动的应用程序。
以上步骤将使用自签名证书配置 Asp.Net Core 项目的 Docker 容器,使其支持 HTTPS。请注意,由于这是自签名证书,浏览器可能会显示安全警告。在生产环境中,建议使用受信任的证书机构签署的证书。