我正在设置运行在带有VS代码的容器中的FastAPI的调试。当我启动调试器时,FastAPI应用程序在容器中运行。但是,当我从主机访问网页时,服务器没有如下响应:

但是,如果使用以下命令从命令行启动容器,则可以从主机访问网页。
docker运行-p 8001: 80 /tcp带-批处理:v2 uvicorn主:app-主机0.0.0.0 -端口80
下面是tasks.json文件:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "docker-run",
"label": "docker-run: debug",
"dockerRun": {
"image": "with-batch:v2",
"volumes": [
{
"containerPath": "/app",
"localPath": "${workspaceFolder}/app"
}
],
"ports": [
{
"containerPort": 80,
"hostPort": 8001,
"protocol": "tcp"
}
]
},
"python": {
"args": [
"main:app",
"--port",
"80"
],
"module": "uvicorn"
}
},
{
"type": "docker-build",
"label": "docker-build",
"platform": "python",
"dockerBuild": {
"tag": "with-batch:v2"
}
}
]}
下面是launch.json文件:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug Flask App",
"type": "docker",
"request": "launch",
"preLaunchTask": "docker-run: debug",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}/app",
"remoteRoot": "/app"
}
],
"projectType": "fastapi"
}
}
]}
以下是调试控制台的输出:

下面是docker运行:调试终端输出:

下面是Python控制台终端的输出:

发布于 2022-03-15 13:57:58
解释
您无法在该端口访问容器的原因是,VSCode使用映射到正在运行的容器的随机唯一本地主机端口构建映像。
通过运行docker container inspect {container_name}可以看到这一点,它应该打印出正在运行的容器的JSON表示形式。在您的例子中,您将编写docker container inspect withbatch-dev
JSON是一个对象数组,在本例中仅为一个对象,其键为"NetworkSettings“,而该对象中的键为”端口“,类似于:
"Ports": {
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "55016"
}
]
}该端口55016将是您可以在localhost:55016连接的端口。
解决方案
通过一些修改和文档,"projectType": "fastapi"似乎应该在特定端口为您启动浏览器。此外,调试控制台的输出显示Uvicorn running on http://127.0.0.1:80。127.0.0.1是localhost (也称为环回接口),这意味着您在对接器容器中的进程只侦听内部连接。想想码头集装箱在它们自己的子网中相对于您的计算机(这有例外,但这并不重要)。如果他们想监听外部连接(您的计算机或其他容器),则需要通知容器的虚拟网络接口。在服务器上下文中,您将使用地址0.0.0.0来指示要侦听引用此接口的所有ipv4地址。
这有点深入,但可以说,您应该能够将--host 0.0.0.0添加到您的运行参数中,并且您将能够连接。您可以在docker运行对象中将其添加到tasks.json中,其中指定了其他python:
{
"type": "docker-run",
"label": "docker-run: debug",
"dockerRun": {
"image": "with-batch:v2",
"volumes": [
{
"containerPath": "/app",
"localPath": "${workspaceFolder}/app"
}
],
"ports": [
{
"containerPort": 80,
"hostPort": 8001,
"protocol": "tcp"
}
]
},
"python": {
"args": [
"main:app",
"--host",
"0.0.0.0",
"--port",
"80"
],
"module": "uvicorn"
}
},https://stackoverflow.com/questions/70277217
复制相似问题