LoginSignup
0
0

【Dev Container】Pythonで実行中のポートにデバッガーをアタッチして、APIをデバッグする

Posted at

前提

Docker環境を構築し、Devcontainerの使用想定

FastAPIでuvicornを使用

Dockerfile

起動コマンドにdebugpy --listen 0.0.0.0:<ポート番号> を追加。ポート番号はなんでもOK。起動コマンド自体はdocker-compose.ymlでも指定可能

requiements.txtにはdebugpyを記載しておく必要がある

FROM python:3.10.13-slim-bullseye

RUN apt-get update &&  apt-get install -y libsndfile1

WORKDIR /usr/src/app

RUN pip install --upgrade pip setuptools

COPY requirements.txt ./
RUN pip install -r requirements.txt

COPY . .

CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "-m", "uvicorn", "api.websocket_server:app", "--host", "0.0.0.0", "--port", "7777"]

docker-compose.yml

ポートを解放

version: '3.7'

services:
  api:
    build: .
    container_name: "api"
    volumes:
      - ./:/usr/src/app
    ports:
    - 8000:8000
    - 5678:5678

launch.json

portはdebugpy --listen 0.0.0.0:<ポート番号> で指定したポートを指定

localRootはホストマシン側のプロジェクトフォルダのパスを指定

remoteRootはDockerコンテナ内のパスを指定

Dockerファイルで、WORKDIR/usr/src/appに指定して、COPY . . を行なっているので、以下のようになる。

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python デバッガー: 起動中のファイルにアタッチ",
      "type": "debugpy",
      "request": "attach",
      "connect": {
        "host": "localhost",
        "port": 5678
      },
      "pathMappings": [
        {
          "localRoot": "${workspaceFolder}",
          "remoteRoot": "/usr/src/app"
        }
      ]
    }
  ]
}

VScodeのデバッグタブから▶️を押してアタッチ

Screenshot 2024-04-12 at 12.39.40.png

弊社Passinate Geniusでは一緒に働く仲間を募集しています!興味をお持ちいただける方は、ホームページまで!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0