VSCode全容器化Python开发环境调试需两次启动的问题求助
问题:VSCode调试容器内Python服务需启动两次才能连接
TL;DR:为何需要启动两次调试,才能让VSCode调试器成功连接到容器内的Python服务?
我正尝试在VSCode中搭建基于容器的Python开发环境,希望直接复用生产环境的容器配置,避免在本地处理Python版本、虚拟环境等问题。我使用VSCode自动生成的部分配置文件,结合教程调整后环境勉强可用,但存在严重问题:必须点击两次「开始调试(F5)」,调试器才能成功连接到容器。
这只是测试项目的情况,在我的实际Python项目中,调试器甚至完全无法连接。我认为当前配置仍有优化空间,特此寻求帮助。以下是我的配置文件:
Dockerfile:
# For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.10-slim # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements COPY requirements.txt . RUN python -m pip install --upgrade pip && \ python -m pip install -r requirements.txt WORKDIR /app COPY . /app # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug CMD ["python", "-m", "testproj"] EXPOSE 80
docker-compose.debug.yml:
version: '3.4' services: testtasks: image: testtasks build: context: . dockerfile: ./Dockerfile command: [ "sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m uvicorn testproj.testproj:app --host 0.0.0.0 --port 80 --reload" ] ports: - 80:80 - 5678:5678 volumes: - ${PWD}:/app
requirements.txt:
fastapi uvicorn
testproj/__main__.py:
import uvicorn uvicorn.run("testproj.testproj:app", host="0.0.0.0", port=80)
testproj/testproj.py:
from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"}
.vscode/tasks.json:
{ "version": "2.0.0", "tasks": [ { "type": "docker-build", "label": "docker-build", "platform": "python", "dockerBuild": { "tag": "testtasks:latest", "dockerfile": "${workspaceFolder}/Dockerfile", "context": "${workspaceFolder}", "pull": true } }, { "label": "Run compose up", "type": "docker-compose", "dockerCompose": { "up": { "detached": true, "build": true }, "files": [ "${workspaceFolder}/docker-compose.debug.yml" ] } }, { "label": "Run compose down", "type": "docker-compose", "dockerCompose": { "down": {}, "files": [ "${workspaceFolder}/docker-compose.debug.yml" ] } } ] }
.vscode/launch.json:
{ "configurations": [ { "name": "Python: Remote Attach", "type": "python", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/app" } ], "preLaunchTask": "Run compose up", "postDebugTask": "Run compose down", "justMyCode": true } ] }
操作现象:第一次点击左上角绿色运行按钮会启动容器,但调试器无法连接;第二次点击调试器成功连接,底部状态栏变为红色,停止功能正常。
内容的提问来源于stack exchange,提问作者mcnesium
相关产品推荐
相关产品推荐

