簡體   English   中英

使用 vscode 從主機調試 docker 容器中運行的 python 代碼

[英]debug python code running in docker container from host using vscode

我有一個容器在我的主機上運行,它有一個 python 進程,並且我在主機上安裝了 vs 代碼。 是否可以從安裝 vscode 的主機調試 python 進程? 如果是,如何實現?

由於我不知道您運行的是什么 python 進程,我將以 FastAPI 為例。

  1. 首先,您需要在文件<project_root>/.vscode/launch.json中定義一個新配置。 要訪問此文件,您可以 go 到活動欄上的運行和調試部分,然后按頂部的 cog/wheel。

配置中添加一個新項目,如下所示。

{
    "version": "0.2.0",
    "configurations": [
        {
        "name": "Python: Remote Attach",
        "type": "python",
        "request": "attach",
        "connect": {
            "host": "localhost",
            "port": 5678
        },
        "pathMappings": [
            {
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "."
            }
        ]
        }
    ]
}
  1. 現在您需要包含debugpy 如果您使用的是需求文件,則可以將其添加到那里。 如果你使用Poetry ,你可以在你的終端中運行poetry add debugpy (Dockerfile 示例展示了如何在 docker 圖像中使用 Poetry)。

  2. 第一個選項- 在您的Dockerfile 中,您需要運行debugpy並使其偵聽端口5678 現在,每次運行容器並等待附件時,調試器都會啟動。

FROM python:3.10.0

# Set the working directory:
WORKDIR /usr/src

# Copy the pyproject.toml file (or requirements.txt) to cache them in the docker layer:
COPY [ "./src/pyproject.toml", "./"]

# Set the python path if needed.
# For example, if main.py is not located in the project root:
ENV PYTHONPATH="$PYTHONPATH:${PWD}"

# Upgrade pip and install Poetry:
RUN pip install --upgrade pip && pip install poetry==1.1.12

# Project initialization using Poetry:
RUN poetry config virtualenvs.create false \
    && poetry install --no-interaction --no-ansi

# Run the application:
CMD ["python", "-m", "debugpy", "--wait-for-client", "--listen", "0.0.0.0:5678", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload", "--reload-exclude", "tests"]

EXPOSE 8000 5678
  1. 第二個選項- 通過添加以下行在 main.py 文件中設置調試器。 這意味着調試器將在啟動時附加到容器; 如果調試器變量設置為 True。
debugger = True

if __name__ == "__main__":
    if debugger:
        import debugpy
        debugpy.listen(("0.0.0.0", 5678))
        debugpy.wait_for_client()

    uvicorn.run(
        "main:app",
        host="localhost",
        port=8000,
        log_level="info",
        reload=True,
    )
  1. 這兩個示例都需要Dockerfile來公開端口5678 現在,運行容器后,調試器將“暫停”並等待附件。 要附加調試器,go 回到 VSCode 和 select Python 的活動欄上的運行和調試部分Python: Remote Attach並從下拉菜單中按下。

現在您應該可以在 docker 容器內使用調試器了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM