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?

Dev Containerについて基礎を学習する

Last updated at Posted at 2024-12-31

Azureで動作するPythonアプリを開発するにあたって、Web AppsはPython 3.12までサポートしているが、Azure FunctionsはPython 3.11までしかサポートしていなかった。メンバーから3.11で統一して開発したいといわれたが、仮想化を使えばなんかもっとよくできるんじゃないかと思いつつ具体的な案を出せず悔しい思いをしたので、以前から気になっていたDev Containerを調査してみる。

環境構築

まずは何はともあれGetting Startedの動画を見る。

Dev Containerを解説している動画に「IT業界に35年いるが、これはまるで魔法のようだ」というコメントがあったが、魔法を使うには魔法の杖の振り方を学ばなくてはならない。環境構築を簡単にするためにはその環境構築が必要ということで。Docker DesktopとWSLだけインストールしてやったら「stream is closed」というエラーになった。

こちらに近いようだが、手間取ったのでまとめる。

ローカル環境設定

以下を諸々インストール。

  • VSCode
  • Devc Container Extension
  • WSL
  • Docker Desktop

WSL

WSLの基本的な使い方はこちら。

WSLからUbuntuのDistroをインストール

Ubuntuを規定にしておく。

PS C:\Work\Python\DevContainer\vscode-remote-try-python> wsl -l
Linux 用 Windows サブシステム ディストリビューション:
Ubuntu (既定)
docker-desktop

Docker Desktop

Docker Desktopの設定から、WSLのUbuntuと統合を使うように設定。
image.png
image.png

VSCodeの設定

VSCodeの設定でDevcontainerで検索して、以下の項目をこうする。
image.png

Devcontainerを設定

Microsoft LearnのModuleがあったので、これに沿って進めていく。

こちらもわかりやすくまとまっていたので、参考にさせていただきました。

Moduleでは、既存のプロジェクトに対してDev Containerを設定していく形で進めているが、新規で作る場合もそんなに変わらない。まずはプロジェクトをgit clone。新規で開発する場合は空のフォルダを開いた状態で始める。

Add Dev Container Configuration Files。
image.png
image.png
このTemplateはかなり幅広く、Python+PostgreSQL、.Net+Azure SQL、Azure Functionsなどもある。Azure FunctionsをDev Containerで開発する用のイメージもあり、しばやんさんが作ってくれたポイ。

Pythonイメージはこちらに詳細があった。

Pythonのバージョンを選ぶ。
image.png

.devcontainerのフォルダができた。
image.png

devcontainer.jsonでベースコンテナイメージ、コンテナ作成後のコマンド実行、Dev Container内のVSCodeを開いた時の拡張機能等を設定できる。

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/python
{
	"name": "Python 3",
	// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
	"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye"

	// Features to add to the dev container. More info: https://containers.dev/features.
	// "features": {},

	// Use 'forwardPorts' to make a list of ports inside the container available locally.
	// "forwardPorts": [],

	// Use 'postCreateCommand' to run commands after the container is created.
	// "postCreateCommand": "pip3 install --user -r requirements.txt",

	// Configure tool-specific properties.
	// "customizations": {},

	// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
	// "remoteUser": "root"
}

Reopen in containerでコンテナを起動する。
image.png

ちなみに最近はGithubのリポジトリでも.devcontainerフォルダを見かけることが多くなったが、そういうプロジェクトは基本的にGit cloneした後にReopenすれば環境を気にすることなくコンテナ上で開くことができる。その際に諸々の依存関係はLocalではなくDev Container上にインストールされるので、ローカルの環境を汚すこともない。

左下がDev Containerになり、コンテナ内で起動できていることがわかる。
image.png

Dev ContainerをVSCodeから開いた状態では、VSCodeの拡張機能も別にインストールする必要がある。確かに考えてみれば、Python開発とC#開発で必要な拡張機能を全部入れてしまったせいで、ローカルのVSCodeの起動が遅くなってしまうような問題がある。Dev Containerを使えば、これは●●開発専用という環境が手に入る。ローカルでインストールされている拡張機能は右クリックからAdd to devcontainer.jsonでDev Container側にもインストールできる。
image.png
、、、はずなのだが、なんかうまく反映されないときがあった。その場合は右にあるIdentifierをdevcontaier.jsonにペーストするといい。

devcontainer.json
"customizations": {
    "vscode": {
        "extensions": [
            "wholroyd.jinja",
        ]
    }
},

その他Dev Containerにツールを入れたい場合はFeature機能が便利。Azure CLIやNodeなども入れることができる。

devcontainer.json
// Features to add to the dev container. More info: https://containers.dev/features.
"features": {
    "ghcr.io/devcontainers/features/azure-cli:1": {},
    "ghcr.io/devcontainers/features/node:1": {
        "version": "18"
    }
},

devcontainer.jsonを更新したら、それを反映させるために最後にRebuildを実行。
image.png

Jupyterを使用するPyhon環境は一旦こんな感じになりました。

devcontainer.json
{
  "name": "Python 3",

  "image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye",

  "runArgs": ["--env-file", ".env"],

  "features": {
    "ghcr.io/devcontainers/features/python:1": {
      "installTools": true,
      "installJupyterlab": true,
      "version": "latest"
    }
  },

  "mounts": [
    "source=vscode-extensions,target=/vscode/.vscode-server/extensions,type=volume",
    {
      "type": "volume",
      "source": "myprj-cache-vscode",
      "target": "/home/vscode/.cache"
    },
    {
      "type": "volume",
      "source": "myprj-venv",
      "target": "${containerWorkspaceFolder}/.venv"
    }
  ],

  "customizations": {
    "vscode": {
      "extensions": [
        "ms-python.python",
        "charliermarsh.ruff",
        "ms-toolsai.jupyter"
      ]
    },
    "settings": {
      "python.defaultInterpreterPath": "/usr/local/bin/python",
      "python.pythonPath": "/usr/local/bin/python"
    }
  },

  "remoteUser": "vscode",

  "postAttachCommand": "sudo chown -R vscode ${containerWorkspaceFolder}/.venv"
}

Dev ContainerからGitに接続

VSCodeの設定がONになっていることを確認。
image.png

これをONにしているだけでローカルのGitの認証情報を引き継げるので、Dev container内からGit Pushなどを行う。

参考情報

  • Rebuild containerすると毎回pip installが必要になる
    → venvをマウントすることで解決。
devcontainer.json
  "mounts": [
    "source=vscode-extensions,target=/root/.vscode-server/extensions,type=volume",
    {
      "type": "volume",
      "source": "myprj-cache-vscode",
      "target": "/home/vscode/.cache"
    },
    {
      "type": "volume",
      "source": "myprj-venv",
      "target": "${containerWorkspaceFolder}/.venv"
    }
  ],

  • Rebuildするとapt-getなどのツールの再インストールが必要になる
    → Dockerfileを使う。

When you make changes like installing new software, changes made in the Dockerfile will persist even upon a rebuild of the dev container.

  • 環境変数
    これは通常のPython開発と同じで.envファイルを使える。これはチェックインしちゃダメなので、gitignoreに追加して管理する。
    image.png
 "runArgs": ["--env-file", ".env"],

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?