如何从 Windows 主机连接到 wsl2 内 docker 容器内的应用程序?

How to connect to app inside docker container inside wsl2 from Windows host?

在 Windows 上:

我刚刚通过 dotnet new mvc 创建了应用程序并为此创建了 Dockerfile:

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 ["src/App.csproj", "src/"]
RUN dotnet restore "src/App.csproj"
COPY . .
WORKDIR "/src/src"
RUN dotnet build "App.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "App.csproj" -c Release -o /app/publish

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

然后我打开 wsl2,进入 /mnt/d/myproject 并构建 docker build -t app . 并启动它。

看到了运行

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9e17cbwe6e4c        test1               "dotnet App.dll"    5 days ago          Up About a minute   80/tcp, 443/tcp     affectionate_goldstine

还有正确的日志:

[10:54:13 WRN] 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.
[10:54:13 INF] User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
[10:54:13 INF] Now listening on: http://[::]:80
[10:54:13 INF] Application started. Press Ctrl+C to shut down.
[10:54:13 INF] Hosting environment: Production
[10:54:13 INF] Content root path: /app/

但我不确定如何连接到它?

您需要使用 -p

公开端口
docker run -itd --name myapp -p 80:80 <image>

然后您可以在 host_ip:80

访问您的应用