17
13

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で安全にclaude codeを使う

Last updated at Posted at 2025-07-22

まとめ

  1. Dev Containerの中でClaude Codeを起動することでプロジェクト内のファイルのみへのアクセスを許可することで意図しないファイルの変更・削除・作成などを避けることができます
  2. claude codeの設定には以下の設定+~/.claudeの永続化が必要です。これでコンテナ再作成してもログイン認証が行われなくなります
    .devcontainer/devcontainer.json
    {
        ...
    	"features": {
    		"ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {},
            ...
    	},
        "mounts": [
            "source=claude-code-config-${devcontainerId},target=/home/vscode/.claude,type=volume"
        ],
    	"containerEnv": {
    		"CLAUDE_CONFIG_DIR": "/home/vscode/.claude"
    	},
    	"containerUser": "vscode"
    }
    
    ※ vscodeは適宜コンテナイメージによって書き換えてください。
  3. Anthropicの公式ページDevelopment containers でも紹介されているように claude --dangerously-skip-permissionsをより安全に使う環境として薦められています。

サンプル

具体的にどうするかが知りたい方はこちらを参照してください。

導入手順

1. Dev Containers Extensionを追加

Screenshot 2025-07-22 at 15.08.45.png

2. 設定ファイルの作成: プロジェクトルートに.devcontainer/devcontainer.jsonを作成

設定ファイルは .devcontainer 以下に配置します。 minimumではdevcontainer.jsonだけを配置すれば使うことができます。

tree .devcontainer/
.devcontainer/
├── Dockerfile <- optinal: Dockerfile使う場合
├── devcontainer.json
└── docker-compose.yml <- optional: docker-composeを使う場合

0 directories, 4 files

.devcontainer/devcontainer.json の設定全体像としては以下のようになります。(ref: devcontainer.json)

Screenshot 2025-07-25 at 12.40.17.png

言語や開発する内容によって異なるので、今回はPythonのケースで紹介します。

2.1. コンテナを準備する

開発コンテナの設定は、3つの方法があります。

  1. 提供されているimageを直接使う (e.g. mcr.microsoft.com/devcontainers/python:1-3.12-bullseye) -> .devcontainer/devcontainer.json内の "image": xxx を書くだけで可
    .devcontainer/devcontainer.json
    {
        "name": "Python Devcontainer",
        "image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye"
      ...
    }
    
  2. 提供されているimageでは足りない場合.devcontainer/Dockerfileを用意する <- devcontainer用のcliやdirectoryなどの設定を自由にできるのでおすすめ
    .devcontainer/devcontainer.json
    {
        "name": "Python Devcontainer",
        "build": {
            "dockerfile": "Dockerfile",
            "context": "."
        }
        ...
    }
    
  3. docker-composeを使う。この場合は、複数のコンテナを使える + devcontainer用のコンテナは上のOption1,2のどちらも使うことができます
    .devcontainer/devcontainer.json
    {
        "name": "Python Devcontainer",
        "dockerComposeFile": "docker-compose.yml",
        ...
    }
    

初めて導入する場合は以下のようなイメージでシンプルなものから始めるのがおすすめです。

  1. まずは提供されているimageを直接使ってみる (e.g. mcr.microsoft.com/devcontainers/python:1-3.12-bullseye)
  2. 必要なfeaturesを探して追加していく (gh, claude, uv, などのcliツールたち)
  3. 提供されているimageでは足りなくなったら Dockerfileを作成してbuildするようにする
  4. DBなど他のコンテナにも接続する必要があれば、docker-compose, docker-in-docker, docker-outside-of-dockerなどを考慮していく

参考までに、Dockerfileは以下のようになります。もちろんこちらもプロジェクトによるので、必要なコマンドなど適宜調整すればよさそうです。このDockerfile自体もClaude Codeに作成してもらいました。

Dockerfile
FROM mcr.microsoft.com/devcontainers/python:3.13

# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive

# Install system packages
RUN apt-get update && apt-get install -y \
    git \
    curl \
    wget \
    vim \
    nano \
    htop \
    tree \
    jq \
    unzip \
    zip \
    build-essential \
    libssl-dev \
    libffi-dev \
    libbz2-dev \
    libreadline-dev \
    libsqlite3-dev \
    libncurses5-dev \
    libncursesw5-dev \
    xz-utils \
    tk-dev \
    libxml2-dev \
    libxmlsec1-dev \
    libffi-dev \
    liblzma-dev \
    # PostgreSQL client for Task7
    postgresql-client \
    # For network checks
    netcat-traditional \
    # For build calculations
    bc \
    # For Docker in Docker support
    docker.io \
    # For container management
    docker-compose \
    # make
    make \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install uv (Python package manager)
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"

# Install pre-commit
RUN pip install pre-commit==4.2.0

# Create workspace directory
WORKDIR /workspace

# Set the default shell to bash
SHELL ["/bin/bash", "-c"]

# Configure git to be safe for the workspace
RUN git config --global --add safe.directory /workspace

# Set up user permissions for vscode user
USER vscode

# Install uv for vscode user
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/home/vscode/.local/bin:$PATH"

# Ensure the workspace is writable by vscode user
RUN sudo chown -R vscode:vscode /workspace

# Set working directory
WORKDIR /workspace

若干不要な設定も入ってるかもしれませんが、適宜調整ということで。

2.2. features

devcontainer features を使うと imageの変更なしで cliなどのツールを追加することができます。

.devcontainer/devcontainer.json
    ...
    "features": { // gh, claude code, uvなどのツールを追加できる
        "ghcr.io/devcontainers/features/github-cli:1": {
            "version": "latest"
        },
        "ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {},
        "ghcr.io/jsburckhardt/devcontainer-features/uv:1": {}
    }

2.3. mounts

コンテナの選択のときに、imageまたはDockerfileで設定している場合には、Docker volumeやホストマシンのファイルやディレクトリのマウント定義を追加することがあります。

例えば、 ~/.claude をコンテナにbindしたり、 zsh historyのディレクトリをマウントする (下の例ではdocker volume にこれらの情報を保存して、devcontainerごとに独立したdocker volumeに保存することもできあmす。)

.devcontainer/devcontainer.json
{
    "mounts": [ // 必要に応じてホストマシンのディレクトリをmountする
        "source=${localEnv:HOME}/.claude,target=/home/vscode/.claude,type=bind",
        "source=${localEnv:HOME}/.zsh_history,target=/home/vscode/.zsh_history,type=bind",
        "source=${localEnv:HOME}/.zshrc,target=/home/vscode/.zshrc,type=bind"
    ],
}

2.4. その他

その他にも initializeCommand, reomoteUser など様々な設定があるので、詳細はdevcontainer.jsonを見ながら必要に応じて設定していくのがいいと思います。

    "initializeCommand": ".devcontainer/init.sh",
    "remoteUser": "vscode",
    "containerUser": "vscode"

2. VS Codeで開く: VS Codeで「Reopen in Container」を選択

mac の場合は command + p でパレットを開いて > dev container とかくと選択肢がでてくるので、Reopen in Container で開きます。

Screenshot 2025-07-22 at 18.04.08.png

3. Claude Codeの確認: コンテナ内でClaude Codeが使用可能か確認

コンテナの中でいつもどおりclaude を叩くとcontainerの中でclaudeを使えるようになります。

claude

Screenshot 2025-07-25 at 12.41.28.png

これによって関係ないホストマシンのファイルを勝手に触られたりすることを防ぐことができます。

Tips

特に初めて設定するときに引っかかることや設定のTipsを書いていきます。

Tip 1. ~/.claudeの設定を永続化する

~/.claude以下に様々なユーザ設定が読み込めないと困ります。

Option1: ホストマシンの~/.claudeをマウントする

.devcontainer/devcontainer.json
  "mounts": [
+    "source=${localEnv:HOME}/.claude,target=/home/vscode/.claude,type=bind"
  ],

ホストマシンの~/.claude以下を読み込むと、共通のUser設定も読み込めるので便利です。

Option2: Docker Volumeにマウントする

Dockerfileを定義する場合は、directoryを作成して権限を付与して、docker volumeにマウントします。

Volumeマウントの場合、プロジェクトごとに完全に分けることができてより安全ではありますが、ローカルのUser設定を引き継ぐことができないので、 User設定に入れているcommandなどが使えなくて不便なことがあります。

# Create claude config directories and set permissions
RUN mkdir -p /home/$USERNAME/.claude && \
  chown -R $USERNAME /home/$USERNAME/.claude

Option2-1: Dockerfile or imageの場合

.devcontainer/devcontainer.json
    ...
	"mounts": [
        ...
+		"source=claude-code-config-${devcontainerId},target=/home/vscode/.claude,type=volume"
	],
    ...

Option2-2: docker-composeの場合

docker-compose.yml
 services:
   devcontainer:
     build: .
     volumes:
       - ../..:/workspaces:cached
+      - claude-code-config:/home/vscode/.claude
     command: sleep infinity
...

 volumes:
+  claude-code-config:

Tip 2. コンテナ再作成時に毎回claude認証しなくてよくする

以下を設定しておくことで、コンテナを再作成しても、~/.claudeを永続化しておけば、毎回のログイン認証が不要になります。

.devcontainer/devcontainer.json
+	"containerEnv": {
+		"CLAUDE_CONFIG_DIR": "/home/vscode/.claude"
+	},

最近 Long-lived authentication tokenがサポートされたので、環境変数にいれたらいけるかなと思って試しましたがだめでした。

Tip 3. claude --dangerously-skip-permissionsを使えるようにする

rootユーザだとclaude --dangerously-skip-permissionsが使えません。

--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons

せっかくdevcontainerにしたのにYOLOできないと困りますね。

userを指定しましょう。(ref: https://code.visualstudio.com/remote/advancedcontainers/add-nonroot-user)

  "removeUser": "vscode"

コンテナ内でwhoamiを打つとvscodeになっています。

whoami
vscode

claude --dangerously-skip-permissionsが使えるようになります!

Screenshot 2025-07-09 at 22.16.19.png

~/はもちろんコンテナ内なので、プロジェクトに関係ないファイルをいじられることはありません。

Tip 4. VSCodeのExtensionをDevcontainerにいれる

customizations.vscode.extensions に追加することでdevcontainerにextensionを追加できる。

{
    ...
+	"customizations": {
+		"vscode": {
+			"extensions": [
+				"shd101wyy.markdown-preview-enhanced"
+			]
+		}
+	},
    ...
}

Tip 5. 使いたいcliをインストールする

最初はDockerfileを使わずに直接 "image": "mcr.microsoft.com/devcontainers/python:3.13"を使おうとしていました。しかし必要なcommandが入っていないケースがあります。

gh: command not found

Devcontainer Featuresを使う

"features": {
    "ghcr.io/devcontainers/features/github-cli:1": {
        "version": "latest"
    }
}

結局他にも必要なコマンドをContainerに入れておく必要があるので、 Dockerfileを作ることにしました。

Claude Codeに作成してもらいました。

参考までDockerfile
FROM mcr.microsoft.com/devcontainers/python:3.13

# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive

# Install system packages
RUN apt-get update && apt-get install -y \
    git \
    curl \
    wget \
    vim \
    nano \
    htop \
    tree \
    jq \
    unzip \
    zip \
    build-essential \
    libssl-dev \
    libffi-dev \
    libbz2-dev \
    libreadline-dev \
    libsqlite3-dev \
    libncurses5-dev \
    libncursesw5-dev \
    xz-utils \
    tk-dev \
    libxml2-dev \
    libxmlsec1-dev \
    libffi-dev \
    liblzma-dev \
    # PostgreSQL client for Task7
    postgresql-client \
    # For network checks
    netcat-traditional \
    # For build calculations
    bc \
    # For Docker in Docker support
    docker.io \
    # For container management
    docker-compose \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install uv (Python package manager)
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"

# Install GitHub CLI
RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
    && chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
    && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
    && apt-get update \
    && apt-get install -y gh \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install pre-commit
RUN pip install pre-commit==4.2.0

# Install make (if not already present)
RUN apt-get update && apt-get install -y make && apt-get clean && rm -rf /var/lib/apt/lists/*

# Create workspace directory
WORKDIR /workspace

# Set the default shell to bash
SHELL ["/bin/bash", "-c"]

# Configure git to be safe for the workspace
RUN git config --global --add safe.directory /workspace

# Set up user permissions for vscode user
USER vscode

# Install uv for vscode user
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/home/vscode/.local/bin:$PATH"

# Ensure the workspace is writable by vscode user
RUN sudo chown -R vscode:vscode /workspace

# Set working directory
WORKDIR /workspace

Tip 6. gitの認証をLocalから共有して使う (自動的にできる)

Sharing Git credentials with your container を使うとホストの認証をコンテナ内で使うことができます。

これがうまく動いていると devcontainer内の ~/.gitconfig[credentials]が以下のようにgit credential helperが指定されている事がわかります。

[credential]
        helper = "!f() { /home/vscode/.vscode-server/bin/xxxxx/node /tmp/vscode-remote-containers-xxxxx.js git-credential-helper $*; }; f"

この時点でgit push git pullなど問題なく行うことができます。

Tip 7. gh認証の簡易化

コンテナに入ってgitは使えるのですが、gh認証は毎回コンテナでgh auth loginをする必要があります。

claude codeではgh commandを使って結構作業してもらうことが多いので、自動的に設定したい気持ちになります。

何もしないと、以下のようなauthを要求するメッセージが出てしまいます。

HTTP 401: This endpoint requires you to be authenticated. (https://api.github.com/graphql)
Try authenticating with:  gh auth login

解決策としては2つありそうです。

  1. GH_TOKENをdevcontainerにセットしてコンテナを起動する
  2. gh auth loginでcredentialsを--unsecure-storageに保存してマウントする

後者はせっかくgh authがkeychainに保存してSecureにCredential情報を管理しているのに反するためWorkaroundとしては、前者を使おうと思います。

こちらの記事で紹介されているやりかたでやります。

.devcontainer/init.sh
#!/bin/bash

# check gh token
if which gh &>/dev/null; then
    gh auth token | xargs -I {} echo "GH_TOKEN="{} > .devcontainer/.env.devcontainer
fi

Dockerfileやimageを使ってる場合は以下のように設定します。

.devcontainer/devcontainer.json
{
    ...
+    "initializeCommand": ".devcontainer/init.sh",
+    "runArgs": [
+        "--env-file",
+        ".devcontainer/.env.devcontainer"
+    ],
    ...
}

docker-composeを使ってる場合には、initializeCommandとenv_fileの設定を書きます。

.devcontainer/devcontainer.json
{
    ...
+    "initializeCommand": ".devcontainer/init.sh",
    ...
}
.devcontainer/docker-compose.yaml
 services:
   devcontainer:
     ...
     env_file:
       ...
+      - .env.devcontainer

.gitignore.env.devcontainerを追加しておきましょう。

これで、devcontainerに入った段階で GH_TOKEN で認証されている状態になります。

gh auth status
github.com
  ✓ Logged in to github.com account nakamasato (GH_TOKEN)
  - Active account: true
  - Git operations protocol: https
  - Token: gho_************************************
  - Token scopes: 'gist', 'read:org', 'repo', 'workflow'

Tip 8. bash/zsh historyを保存する

Persist bash history

Docker volumeに保存します。カスタムイメージを使う必要があります。Dockerfileに以下を追加します。

ARG USERNAME=vscode

# Used to persist bash history as per https://code.visualstudio.com/remote/advancedcontainers/persist-bash-history
RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \
    && mkdir /commandhistory \
    && touch /commandhistory/.bash_history \
    && chown -R $USERNAME /commandhistory \
    && echo "$SNIPPET" >> "/home/$USERNAME/.bashrc"

Volume を /commandhistory にマウント:

Option1: Dockerfile or imageを使ってる場合は、devcontainer.json内で定義します。

devcontainer.json
{
    ...
	"mounts": [
        ...
+		"source=commandhistory-${devcontainerId},target=/commandhistory,type=volume"
	],
    ...
}

Option2: docker-composeを使ってる場合は、volumeとmountを追加します。

.devcontainer/docker-compose.yaml
 services:
   devcontainer:
     build: .
     volumes:
       - ../..:/workspaces:cached
+      - commandhistory:/commandhistory
     command: sleep infinity
...

 volumes:
+  commandhistory:

zshの場合もほとんど同じです。 ~/.zshrc にHISTFILEを設定すればOKです。

echo 'export HISTFILE=/commandhistory/.zsh_history' >> "/home/$USERNAME/.zshrc"

Tip 9. ~/.cache をマウントする

pre-commitなどは~/.cacheにキャッシュを置くので同様にVolumeを用意する

# Create cache directory and set permissions
RUN mkdir -p /home/$USERNAME/.cache && \
  chown -R $USERNAME /home/$USERNAME/.cache
docker-compose.yml
  services:
    devcontainer:
      build: .
      volumes:
+       - cache:/home/vscode/.cache

  volumes:
...
+   cache:

Tip 10. Dockerをdevcontainerの中から使う

DBをDockerで立ち上げたりしているケースだとdevcontainerの中からDockerコンテナへアクセスが必要になるので、いくつかの方法があります。

  1. Docker-in-Docker: Docker デーモンをdevcontainer内で立ち上げて使う
  2. Docker-outside-of-Docker: ホストのDockerデーモンを共有する (Example: docker-outside-of-docker-compose
  3. docker-composeを使う (https://code.visualstudio.com/docs/devcontainers/create-dev-container#_use-docker-compose)
    1. Example: Python3 + PostgreSQL

個人的には、docker compose を使うのがなんだかんだ一番楽かなと思い、普段Devcontainerを導入する際には、Docker-composeで設定するようにしています。
あとから、必要なコンテナを追加するときにDevcontainerの全体の設定をいじらなくて済むためです。

Tip 11. pre-commitを自動でinstallしたい

.devcontainer/post-start.sh を用意してその中に pre-commit install など書いて置くことができます。

.devcontainer/post-start.sh
#!/bin/bash

pre-commit install
.devcontainer/devcontainer.json
{
    ...
    "postStartCommand": ".devcontainer/post-start.sh",
}

Tip 12. Claude Codeが --no-verifyして pre-commitをスキップするのを防ぐ

.devcontainer/devcontainer.json
    "postCreateCommand": "bash .devcontainer/setup-git-hooks.sh",
.devcontainer/setup-git-hooks.sh
#!/bin/bash

# Add git function to prevent --no-verify usage
cat >> ~/.zshrc << 'EOF'
git() {
    if [[ "$1" == "commit" ]]; then
        for arg in "$@"; do
            if [[ "$arg" == "--no-verify" || "$arg" == "-n" ]]; then
                echo "❌ ERROR: --no-verify bypasses quality checks and is forbidden"
                echo "Pre-commit hooks ensure code quality. Please fix issues instead of bypassing them."
                return 1
            fi
        done
    fi
    command git "$@"
}
EOF

git に --no-verify をつけたときに失敗するように設定しておく。この例では ~/.zshrcに追記しているが、bashの場合は ~/.bashrc に変えます。

AIエージェントによる git commit --no-verify を完全に防ぐ方法で紹介されていたのをDevcontainerでも使えるように設定しています。

Tip 13. Devcontainerから抜けたい

意外と最初はDevcontainerからの抜け方がわからないことがあります。

Reopen Folder Locally でDevcontainerから抜けられます。

Screenshot 2025-07-22 at 18.03.52.png

Appendix: https://github.com/nakamasato/flask-sample にdevcontainerを導入するステップ紹介

Step1: 最低限のPython imageでDevcontainer起動

.devcontainer/devcontainer.json
{
	"name": "Python 3",
	"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye",
	"features": {
		"ghcr.io/devcontainers/features/github-cli:1": {},
		"ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {},
		"ghcr.io/devcontainers-extra/features/poetry:2": {},
        "ghcr.io/devcontainers-extra/features/pre-commit:2": {}
	},
	"remoteUser": "vscode",
	"containerUser": "vscode"
}

この時点で、

  • source codeへのアクセス、 gitへのアクセスができる
  • gh command, claude code, poetry, pre-commit が使えるようになる

Step2: Docker ComposeにしてDBも使えるようにする

このレポではflask appがmysqlへ接続する構成なので、devcontainerでもmysql containerが必要

.devcontainer/docker-compose.yml
version: '3.8'
services:
  devcontainer:
    image: "mcr.microsoft.com/devcontainers/python:1-3.12-bullseye"
    volumes:
      - ../..:/workspaces:cached
    env_file:
      - ../docker/env_file/env.app
      - ../docker/env_file/env.mysql
    command: sleep infinity
    ports:
      - 8000:5000

  mysql:
    image: mysql:8.0
    restart: unless-stopped
    volumes:
      - db_data:/var/lib/mysql
      - ../docker/mysql/schema/user.sql:/docker-entrypoint-initdb.d/01_schema_user.sql
      - ../docker/mysql/data/user.sql:/docker-entrypoint-initdb.d/11_data_user.sql
      - ../docker/mysql/conf.d/:/etc/mysql/conf.d/
    env_file:
      - ../docker/env_file/env.mysql
    ports:
      - 3306:3306
    healthcheck:
      test: ["CMD", "mysqladmin", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  db_data:
.devcontainer/devcontainer.json
{
	"name": "Python 3",
	"dockerComposeFile": "docker-compose.yml",
	"service": "devcontainer",
    "workspaceFolder": "/workspaces/flask-sample", 
	"features": {
		"ghcr.io/devcontainers/features/github-cli:1": {},
		"ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {},
		"ghcr.io/devcontainers-extra/features/poetry:2": {},
        "ghcr.io/devcontainers-extra/features/pre-commit:2": {}
	},
	"remoteUser": "vscode",
	"containerUser": "vscode"
}

これでflaskが立ち上がるようになる FLASK_APP=sample FLASK_ENV=development poetry run flask run --host=0.0.0.0

Screenshot 2025-07-22 at 17.19.56.png

8000:5000をportsに設定しているので、hostのlocalhost:8000でdevcontainerの5000 portにアクセスできる。

curl localhost:8000/health
{"status":"healthy"}

Step3: 最終盤

  • Dockerfile 作成
    • .zsh_history, ~/.claude のマウント
    • tigコマンドインストール
  • pre-commit installをcontainer開始時に実行
  • gh auth tokenをGH_TOKENに設定
  • Shellをzshにする
tree .devcontainer/
.devcontainer/
├── Dockerfile
├── devcontainer.json
└── docker-compose.yml

0 directories, 3 files
.devcontainer/Dockerfile
FROM mcr.microsoft.com/devcontainers/python:1-3.12-bullseye

ARG USERNAME=vscode

# Install tig
RUN apt-get update && apt-get install -y tig && apt-get clean

# Used to persist shell history
RUN mkdir /commandhistory \
    && touch /commandhistory/.bash_history \
    && touch /commandhistory/.zsh_history \
    && chown -R $USERNAME /commandhistory \
    && echo 'export PROMPT_COMMAND="history -a" && export HISTFILE=/commandhistory/.bash_history' >> "/home/$USERNAME/.bashrc" \
    && echo 'export HISTFILE=/commandhistory/.zsh_history' >> "/home/$USERNAME/.zshrc"

# Create claude config directories and set permissions
RUN mkdir -p /home/$USERNAME/.claude && \
  chown -R $USERNAME /home/$USERNAME/.claude

.devcontainer/devcontainer.json
{
	"name": "Python 3",
	"dockerComposeFile": "docker-compose.yml",
	"service": "devcontainer",
	"workspaceFolder": "/workspaces/flask-sample",
	"features": {
		"ghcr.io/devcontainers/features/github-cli:1": {},
		"ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {},
		"ghcr.io/devcontainers-extra/features/poetry:2": {},
		"ghcr.io/devcontainers-extra/features/pre-commit:2": {},
		"ghcr.io/devcontainers/features/common-utils:2": {
			"installZsh": true,
			"installOhMyZsh": true,
			"configureZshAsDefaultShell": true
		}
	},
	"customizations": {
		"vscode": {
			"extensions": [
				"shd101wyy.markdown-preview-enhanced"
			]
		}
	},
	"containerEnv": {
		"CLAUDE_CONFIG_DIR": "/home/vscode/.claude"
	},
	"postStartCommand": "pre-commit install",
	"initializeCommand": "echo \"GH_TOKEN=$(gh auth token)\" > .devcontainer/.env.devcontainer",
	"containerUser": "vscode"
}
.devcontainer/docker-compose.yml
services:
  devcontainer:
    build: .
    volumes:
      - ../..:/workspaces:cached
      - commandhistory:/commandhistory
      - claude-code-config:/home/vscode/.claude
    env_file:
      - ../docker/env_file/env.app
      - ../docker/env_file/env.mysql
      - .env.devcontainer
    command: sleep infinity
    ports:
      - 8000:5000

  mysql:
    image: mysql:8.0
    restart: unless-stopped
    volumes:
      - db_data:/var/lib/mysql
      - ../docker/mysql/schema/user.sql:/docker-entrypoint-initdb.d/01_schema_user.sql
      - ../docker/mysql/data/user.sql:/docker-entrypoint-initdb.d/11_data_user.sql
      - ../docker/mysql/conf.d/:/etc/mysql/conf.d/
    env_file:
      - ../docker/env_file/env.mysql
    ports:
      - 3306:3306
    healthcheck:
      test: ["CMD", "mysqladmin", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  db_data:
  commandhistory:
  claude-code-config:

TODO

参考

17
13
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
17
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?