1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flask+Docker+VSCodeでFlaskのコンテナへリモートデバッグしよう!

Last updated at Posted at 2024-12-13

概要

【Flask+Docker】の開発環境をVSCodeでリモートデバッグする方法について解説します
リモードデバッグする際は拡張機能のRemote Containersを使用します
VSCodeのブレークポイントやウォッチが使えるとかなり開発効率が上がるのでぜひ設定してみてください
記事の後半ではPoetryを使ってリモートデバッグする方法についても解説します

前提

  • すでにFlaskのプロジェクトをgit cloneしている
  • VSCodeをインストール済み
  • Dockerをインストール済み
  • Remote Containersを使用します
  • Dockerfileおよびdocker-compose.ymlはある程度読める方が望ましい
  • ブレークポイント、ウォッチの解説はしません

コンテナイメージを作成しよう

Remote Containersを使うには該当コンテナのイメージをbuildする必要があります
docker-composeの構成は以下のように設定し、デバッグ用の8080番ポートを開放します

docker-compose.yml
version: "3.9"

services:
  db:
    container_name: db
    build:
      context: .
      dockerfile: containers/postgres/Dockerfile
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: pg_isready -U "${POSTGRES_USER:-postgres}" || exit 1
      interval: 10s
      timeout: 5s
      retries: 5
    environment:
      - POSTGRES_NAME
      - POSTGRES_USER
      - POSTGRES_PASSWORD
    ports:
      - "5432:5432" # デバッグ用
  app:
    container_name: app
    build:
      context: .
      dockerfile: containers/flask/Dockerfile
    volumes:
      - ./application:/code
    ports:
      - 8000:8000
      # デバッグ用ポート
      - 8080:8080
    command: poetry run flask --app main run --debug -h 0.0.0.0 -p 8000
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy
volumes:
  db_data:

Remote Containersのインストール

まずは拡張機能のRemote Containersをインストールします
スクリーンショット 2022-08-21 21.23.30.png

該当するコンテナへリモート接続しよう

Remotes Containerのインストールができたら左下の緑色のマークをクリックします
スクリーンショット 2022-08-21 21.24.12.png

ボタンを押すとコマンドパレットが開くのでAdd Development Container Configuration Filesを選択します
スクリーンショット 2022-08-21 21.22.17.png

リモート接続するコンテナイメージを作成するdocker-composeファイルを選択します
スクリーンショット 2022-08-21 21.22.40.png

該当するコンテナ名を選択します
スクリーンショット 2022-08-21 21.24.44.png

コンテナ名を選択すると.devcontainerフォルダが作成され、その中に

  • devcontainer.json
  • docker-compose.yml

が作成されます。devcontainer.jsonに必要な情報を入力していきます

devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-docker-compose
{
	"name": "flask container",
	"dockerComposeFile": [
		"../docker-compose.yml"
	],
    "service": "app",
	"workspaceFolder": "/code"
}

Open Folder in Containerから該当するプロジェクトのディレクトリを開きます
スクリーンショット 2022-08-21 21.36.39.png

2回目以降はAttach to Running Containerから開くこともできます
スクリーンショット 2022-11-20 20.13.53.png

該当するプロジェクトのディレクトリを開くとコンテナにリモート接続できます
スクリーンショット 2022-08-21 21.29.20(2).png

FlaskのデバッグをするにはPythonとPython Debuggerの拡張機能をインストールする必要があります
スクリーンショット 2022-08-21 21.38.07.png

スクリーンショット 2024-09-12 14.33.59.png

VSCodeのブレークポイントやウォッチが使えるよう設定します
実行とデバッグを選択し、launch.jsonファイルを作成しますを押します
スクリーンショット 2022-08-21 21.37.17.png

デバッガーはPythonを選択します
スクリーンショット 2022-08-21 21.40.05.png

フレームワークはFlaskを選択します
スクリーンショット 2024-09-12 14.34.40.png

launch.jsonに必要な情報を入力します
記事によってはtypeの箇所をpythonにしているものもありますが2024年1月から非推奨になっているのでdebugpyにしましょう

launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Flask Debugger",
            "type": "debugpy",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "main.py",
                "FLASK_DEBUG": "1"
            },
            "args": [
                "run",
                "-h",
                "0.0.0.0",
                "-p",
                "8080",
            ],
            "justMyCode": false,
            "jinja": true,
            "autoStartBrowser": false
        }
    ]
}

debugpyを使うことでVSCodeのPythonの拡張機能のバージョンを落とさずに古いバージョンを使っているPythonのバージョンでリモートデバッグできるとのことです
詳細は以下の通りです

The Python Debugger extension aims to separate the debugging functionality from the main Python extension to prevent compatibility issues. This ensures that even as the Python extension drops support for older Python versions (for example, Python 3.7), you can continue debugging projects with those versions without downgrading your Python extension. It also delivers platform-specific builds, ensuring you only receive the components relevant to your specific operating system, reducing download times and unnecessary overhead.

To ensure you are using the new Python Debugger extension, replace "type": "python" with "type": "debugpy" from your launch.json configuration file. In the future, the Python extension will no longer offer debugging support, and we will transition all debugging support to the Python Debugger extension for all debugging functionality.

緑の実行ボタンを押してデバッグを実行します
スクリーンショット 2024-09-12 14.41.07.png

任意の箇所にブレークポイントを設定します
ブレークポイントが実行できれば成功です

スクリーンショット 2024-12-13 19.00.24.png

justMyCode: false

justMyCode: false

にすることで下記の様に自分が書いたコード以外の箇所でデバッグできます

スクリーンショット 2024-12-13 19.00.55.png

Poetryを使ってデバッグする時

Poetryを使用している場合はインタプリンタのパスをPoetryのVirtualenvのPythonのパスを指定する必要があります

poetry env info

を実行するとVirtualenvとSystemの情報が表示されます

Virtualenv
Python:         3.12.8
Implementation: CPython
Path:           /root/.cache/pypoetry/virtualenvs/flask-practice-MATOk_fk-py3.12
Executable:     /root/.cache/pypoetry/virtualenvs/flask-practice-MATOk_fk-py3.12/bin/python
Valid:          True

Base
Platform:   linux
OS:         posix
Python:     3.12.8
Path:       /usr/local
Executable: /usr/local/bin/python3.12

VirualenvのExecutableのパスをコピーし、VSCodeのコマンドパレットからインタプリンタをVirtualenvのExecutableのパスを設定します

スクリーンショット 2024-12-13 18.58.16.png

参考文献

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?