目的
ローカル環境にPythonを入れずに開発を行いたい時に、ローカル環境に Python を直接インストールせずに、Docker を活用して FastAPI の開発環境を整えます。これにより、環境の再現性が高まり、異なるマシンでも同じ環境を構築しやすくなります
※本記事では Docker を使った FastAPI のデバッグ環境構築について解説します。ただし、VisualStudioCode の Dev Containers を使う方法もあるので、そちらを検討するのも良いです
環境
前提
- dockerおよびdocker-composeが実行できる環境
- Visual Studio Codeが実行できる環境
- Visual Studio Codeの拡張機能がインストールできる環境
- Proxy内ではない環境
以下のようなディレクトリ構成でファイルを配置してください
python-docker-debug
│ debug-docker-compose.yml
│ debug.Dockerfile
│ requirements.txt
│
├─.vscode
│ launch.json
│ tasks.json
│
└─app
└─src
main.py
構築
VisualStudioCodeの拡張機能をインストール
ms-python.python
: Python開発の便利ツールms-python.debugpy
: Pythonのデバッガー (ms-python.python
をインストールすると自動でインストールされる)ms-python.vscode-pylance
: Pythonのコード補完、型チェック、リファクタリング支援など(ms-python.python
をインストールすると自動でインストールされる)
ファイルの用意
docker
./debug-docker-compose.yml
version: '3.7'
services:
server:
container_name: myfastapi
build:
context: .
dockerfile: ./debug.Dockerfile
restart: always
volumes:
- ./app/src:/src
ports:
- 8000:8000
- 5678:5678
./debug.Dockerfile
# ベースイメージ(amd64 の Python 3.13.2)
FROM --platform=linux/amd64 python:3.13.2
# システムパッケージを更新&ビルドツールをインストール
RUN apt update -y && apt upgrade -y && apt-get install -y build-essential \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
# アプリケーションのコードをコピー
COPY app/src /src
# requirements.txt をコピーして、必要な Python パッケージをインストール
COPY requirements.txt /src
RUN pip install --upgrade pip && pip install -r requirements.txt
# 作業ディレクトリを設定
WORKDIR /src
# コンテナ起動時のコマンド(デバッグ + Uvicorn 実行)
CMD ["python3", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"]
./requirements.txt
fastapi
uvicorn
python-multipart
debugpy
VisualStudioCodeの実行とデバッグ設定
./.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "debugpy",
"request": "attach",
"name": "FastAPI Remote Debug",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}/app/src",
"remoteRoot": "/src"
}
],
"preLaunchTask": "Run FastAPI with Docker Compose"
}
]
}
./.vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Run FastAPI with Docker Compose",
"type": "shell",
"command": "docker-compose",
"args": [
"-f",
"debug-docker-compose.yml",
"up",
"--build"
],
"isBackground": true,
"problemMatcher": []
}
]
}
FastAPIのサンプルコード
./app/src/main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
実行とデバッグ
実行
Shift
+Ctrl
+P
でTasks: Run Task
を選んで EnterRun FastAPI with Docker Compose
を選んで Enter- docker ps を実行し、myfastapi コンテナが起動していることを確認する。 これでDockerイメージがビルドされて起動する
デバッグの実行
main.py
を開き 8行あたりでブレイクポイントを置くF5
ボタンを押すかShift
+Ctrl
+D
を押してFastAPI Remote Debug
を選択し実行 これでdocker上で動いているdebugpyの5678ポートにアタッチしてくれる
リクエストを投げる
基本的に何でもいいのですが、ブラウザのURL欄に http://localhost:8000
を入力して移動するとリクエストを出してデバッグが拾ってくれる
コメント