1
1

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 Containersで開発環境を統一する - 環境構築の悩みを解決

Posted at

Dev Containersで開発環境を統一する - 環境構築の悩みを解決

はじめに

「このプロジェクト、私のマシンでは動かないんです...」「新しいメンバーの環境構築に丸一日かかりました」このような経験はありませんか?開発チームが抱える環境構築の課題を解決する強力なツールがDev Containersです。

Dev Containersは、開発環境をDockerコンテナ内で統一し、チーム全体で同じ環境を共有できる仕組みです。Visual Studio CodeやGitHub Codespacesと組み合わせることで、誰でも簡単に一貫した開発環境を構築できます。

Dev Containersとは

Dev Containers(Development Containers)は、開発環境をコンテナ化する仕様です。プロジェクトのルートディレクトリに.devcontainerフォルダを配置し、その中で環境の設定を定義します。

主な特徴

環境の統一: チーム全員が同じ開発環境で作業できます。OSやツールのバージョン違いによる問題を回避できます。

簡単なセットアップ: 新しいメンバーは、リポジトリをクローンしてコンテナを起動するだけで開発を始められます。

分離された環境: プロジェクトごとに独立した環境を持てるため、他のプロジェクトとの干渉を防げます。

クラウド対応: GitHub CodespacesやGitpodなどのクラウド開発環境でも同じ設定を使用できます。

基本的な構成

Dev Containersの設定は.devcontainerディレクトリ内のdevcontainer.jsonファイルで行います。

project-root/
├── .devcontainer/
│   ├── devcontainer.json
│   └── Dockerfile (オプション)
├── src/
└── README.md

devcontainer.jsonの基本構造

{
  "name": "My Project",
  "image": "mcr.microsoft.com/devcontainers/typescript-node:18",
  "features": {
    "ghcr.io/devcontainers/features/git:1": {},
    "ghcr.io/devcontainers/features/github-cli:1": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-vscode.vscode-typescript-next",
        "esbenp.prettier-vscode"
      ]
    }
  },
  "forwardPorts": [3000],
  "postCreateCommand": "npm install"
}

実践的な設定例

Node.js開発環境

{
  "name": "Node.js Development",
  "image": "mcr.microsoft.com/devcontainers/typescript-node:18",
  "features": {
    "ghcr.io/devcontainers/features/git:1": {},
    "ghcr.io/devcontainers/features/github-cli:1": {},
    "ghcr.io/devcontainers/features/docker-in-docker:2": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-vscode.vscode-typescript-next",
        "esbenp.prettier-vscode",
        "bradlc.vscode-tailwindcss",
        "ms-vscode.vscode-json"
      ],
      "settings": {
        "typescript.preferences.quoteStyle": "single",
        "editor.formatOnSave": true
      }
    }
  },
  "forwardPorts": [3000, 5000],
  "postCreateCommand": "npm install && npm run build",
  "remoteUser": "node"
}

Python開発環境

{
  "name": "Python Development",
  "image": "mcr.microsoft.com/devcontainers/python:3.11",
  "features": {
    "ghcr.io/devcontainers/features/git:1": {},
    "ghcr.io/devcontainers/features/github-cli:1": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-python.python",
        "ms-python.pylint",
        "ms-python.black-formatter",
        "ms-toolsai.jupyter"
      ]
    }
  },
  "postCreateCommand": "pip install -r requirements.txt",
  "remoteUser": "vscode"
}

カスタムDockerfileを使用した環境

複雑な環境が必要な場合は、カスタムDockerfileを作成できます。

FROM mcr.microsoft.com/devcontainers/base:ubuntu

# 必要なパッケージをインストール
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    git \
    && rm -rf /var/lib/apt/lists/*

# Node.jsをインストール
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
    && apt-get install -y nodejs

# Pythonをインストール
RUN apt-get update && apt-get install -y python3 python3-pip

USER vscode

対応するdevcontainer.json:

{
  "name": "Custom Environment",
  "build": {
    "dockerfile": "Dockerfile"
  },
  "features": {
    "ghcr.io/devcontainers/features/git:1": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-vscode.vscode-typescript-next",
        "ms-python.python"
      ]
    }
  },
  "postCreateCommand": "npm install && pip install -r requirements.txt"
}

Featuresの活用

Dev Container Featuresは、環境に追加機能を簡単にインストールできる仕組みです。

よく使用されるFeatures

{
  "features": {
    "ghcr.io/devcontainers/features/git:1": {},
    "ghcr.io/devcontainers/features/github-cli:1": {},
    "ghcr.io/devcontainers/features/docker-in-docker:2": {},
    "ghcr.io/devcontainers/features/aws-cli:1": {},
    "ghcr.io/devcontainers/features/terraform:1": {
      "version": "1.5"
    },
    "ghcr.io/devcontainers/features/kubectl-helm-minikube:1": {}
  }
}

Docker Composeとの組み合わせ

複数のサービスが必要なプロジェクトでは、Docker Composeと組み合わせて使用できます。

docker-compose.yml

version: '3.8'
services:
  app:
    build:
      context: .
      dockerfile: .devcontainer/Dockerfile
    volumes:
      - ..:/workspaces:cached
    command: sleep infinity
    depends_on:
      - db
      - redis

  db:
    image: postgres:15
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password
    volumes:
      - postgres-data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine

volumes:
  postgres-data:

devcontainer.json

{
  "name": "Full Stack Development",
  "dockerComposeFile": "docker-compose.yml",
  "service": "app",
  "workspaceFolder": "/workspaces",
  "features": {
    "ghcr.io/devcontainers/features/git:1": {}
  },
  "customizations": {
    "vscode": {
      "extensions": [
        "ms-vscode.vscode-typescript-next",
        "ms-python.python"
      ]
    }
  },
  "forwardPorts": [3000, 5432, 6379],
  "postCreateCommand": "npm install"
}

VS Codeでの使用方法

拡張機能のインストール

Dev Container拡張機能をインストールします:

  • 拡張機能タブで「Dev Containers」を検索
  • Microsoftが提供する「Dev Containers」拡張機能をインストール

コンテナでの開発開始

  1. プロジェクトをVS Codeで開く
  2. コマンドパレット(Ctrl+Shift+P)を開く
  3. 「Dev Containers: Reopen in Container」を実行
  4. コンテナがビルドされ、コンテナ内でVS Codeが開く

リモートでの開発

{
  "remoteUser": "vscode",
  "workspaceFolder": "/workspace",
  "mounts": [
    "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached"
  ]
}

最適化のテクニック

ビルド時間の短縮

{
  "build": {
    "dockerfile": "Dockerfile",
    "context": "..",
    "args": {
      "BUILDKIT_INLINE_CACHE": "1"
    }
  },
  "mounts": [
    "source=devcontainer-cache,target=/var/cache,type=volume"
  ]
}

環境変数の設定

{
  "containerEnv": {
    "NODE_ENV": "development",
    "DEBUG": "app:*"
  },
  "remoteEnv": {
    "PATH": "${containerEnv:PATH}:/usr/local/bin"
  }
}

パフォーマンス向上

{
  "mounts": [
    "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached",
    "source=node_modules,target=/workspace/node_modules,type=volume"
  ],
  "runArgs": ["--cpus=2", "--memory=4g"]
}

チーム運用のベストプラクティス

バージョン管理

devcontainer.jsonはバージョン管理に含めて、チーム全体で同じ設定を共有します。

{
  "name": "Project v2.1",
  "image": "mcr.microsoft.com/devcontainers/typescript-node:18-bullseye",
  "features": {
    "ghcr.io/devcontainers/features/git:1": {
      "version": "2.40"
    }
  }
}

ドキュメント化

READMEファイルに環境構築手順を記載します:

## 開発環境セットアップ

1. VS CodeのDev Containers拡張機能をインストール
2. このリポジトリをクローン
3. VS Codeで開き、「Reopen in Container」を実行
4. `npm start`で開発サーバーを起動

CI/CDとの統合

# .github/workflows/test.yml
name: Test
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build Dev Container
        uses: devcontainers/ci@v0.3
        with:
          imageName: my-project-dev
          runCmd: npm test

トラブルシューティング

よくある問題と解決方法

コンテナが起動しない

  • Dockerが正しく動作しているか確認
  • .devcontainer/devcontainer.jsonの構文エラーをチェック
  • イメージの存在確認

拡張機能が動作しない

  • customizations.vscode.extensionsに適切に記載されているか確認
  • 拡張機能の依存関係を確認

ファイルの変更が反映されない

  • マウント設定を確認
  • ファイル監視の制限を確認

デバッグ設定

{
  "customizations": {
    "vscode": {
      "launch": {
        "version": "0.2.0",
        "configurations": [
          {
            "name": "Debug Node.js",
            "type": "node",
            "request": "launch",
            "program": "${workspaceFolder}/src/index.js",
            "env": {
              "NODE_ENV": "development"
            }
          }
        ]
      }
    }
  }
}

まとめ

Dev Containersは、開発環境の統一と効率化を実現する強力なツールです。適切に設定することで、チーム全体の生産性向上とオンボーディングの簡素化を実現できます。

小さなプロジェクトから始めて、徐々に設定を充実させていくことをお勧めします。チーム内で設定を共有し、継続的に改善していくことで、より良い開発体験を構築できるでしょう。

Dev Containersを活用して、「環境構築で困る」ことのない、スムーズな開発フローを実現してください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?