为什么在 Visual Studio 中结束调试后我的 docker 容器 ASP.NET 核心应用程序不可用

Ada*_* M. 5 visual-studio iis-express docker dockerfile asp.net-core

我的标题解释了其中的大部分内容,但想了解为什么我在 Visual Studio 中调试时可以访问https://localhost:32770/并获取我的 API 端点,但是当我结束调试时它变得不可用。

我目前正忙着花几天的时间来研究 Docker 和 Kubernetes,这让我有点困惑,我真的很想填补我的知识空白。

容器在创建后保持运行,那么发生了什么变化?

我注意到这是在构建开始时运行的:

docker exec -i 0f855d9b4c801bf8c52da48e6dd02ffdf0fe7242fde22fb9a221616e4b2900f9 /bin/sh \
-c "if PID=$(pidof dotnet); then kill $PID; fi"
Run Code Online (Sandbox Code Playgroud)

但我没有看到在运行 dockerfile 和一切之前调试结束后会发生什么变化。我不明白命令中的 -c,但我明白引号中的脚本在容器中运行后遵循docker exec语法docker exec [OPTIONS] CONTAINER COMMAND [ARG...]. 似乎这个脚本在创建新代码之前杀死了现有的代码构建。

这是在运行 dockerfile 之前运行的

docker build -f "F:\Dev\API_files\API_name\Dockerfile" 
--force-rm 
-t API_name:dev 
--target base  
--label "com.microsoft.created-by=visual-studio" 
--label "com.microsoft.visual-studio.project-name=API_name" "F:\Dev\API_name"
Run Code Online (Sandbox Code Playgroud)

我在这里没有看到任何会改变容器运行方式的东西,在这个实例中 rm '在构建后删除中间容器(默认为真)'根据 docker build --help

接下来运行 dockerfile,它几乎是 ASP.NET 核心应用程序的默认文件,它具有

EXPOSE 80
EXPOSE 443
Run Code Online (Sandbox Code Playgroud)

其余的都是简单的构建步骤。毕竟,我似乎无法找到太多关于正在发生的事情的迹象。我的猜测是它与 IIS Express 有关,但实际上我不太了解它发生了什么以及 Visual Studios 何时进行调试。在我调试以打开 docker 容器的 localhost 端口时,正在运行的幕后发生了什么?

编辑:我发现一个 docker run 命令可能与它有关,但也许不是。docker run 命令具有“将-P所有暴露的端口发布到随机端口”的标志,但容器永远不会停止运行,所以我是否应该无法找到这些端口并连接到 API?

小智 6

调试过程中,如果执行以下命令:

docker exec -it containerName bash -c 'pidof dotnet'
Run Code Online (Sandbox Code Playgroud)

您会注意到,dotnet 进程正在运行,当您停止调试并再次运行它时,您将看到该进程已完成。

如果您想在容器中启动应用程序,而无需再次运行调试器,则只需dotnet在容器内运行启动进程即可。

您可以通过运行如下脚本来做到这一点:

#Set these 3 variables
$containerName = "MyContainer"
$appDll = "myApp.dll"
$appDirectory = "/app/bin/debug/netcoreapp3.1"

$args = "/c docker exec -it $containerName bash -c 'cd $appDirectory;dotnet $appDll'"
Start-Process -FilePath "powershell" -ArgumentList $args -NoNewWindow
Run Code Online (Sandbox Code Playgroud)

您可以通过再次运行此脚本来检查它是否有效:

#Set these 3 variables
$containerName = "MyContainer"
$appDll = "myApp.dll"
$appDirectory = "/app/bin/debug/netcoreapp3.1"

$args = "/c docker exec -it $containerName bash -c 'cd $appDirectory;dotnet $appDll'"
Start-Process -FilePath "powershell" -ArgumentList $args -NoNewWindow
Run Code Online (Sandbox Code Playgroud)