🐳

権限問題を解消した .devcontainer のテンプレート

に公開

概要

VSCodeのdevcontainerは開発環境をそろえる点からすごく便利だが、UIDなどをホストと揃えないと権限の問題が生じていろいろ面倒くさい。そこで権限問題を解消済みの.devcontainerディレクトリのテンプレートをここにメモしておく。好きに使ってほしい。

内容

.devcontainer/compose.yaml
services:
  devel:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        UID: ${HOST_UID:-20000}
        GID: ${HOST_GID:-20000}
    volumes:
      - ..:/workspace
    working_dir: /workspace
    tty: true
.devcontainer/Dockerfile
FROM ubuntu:latest

RUN apt update && apt-get --no-install-recommends install -y \
    build-essential \
    git wget curl ca-certificates \
    python3


ARG UID=20000
ARG GID=20000
RUN set -eux; \
    # 既存ユーザー・グループを安全に削除
    if getent passwd "${UID}" >/dev/null; then \
        olduser=$(getent passwd "${UID}" | cut -d: -f1); \
        echo "UID ${UID} already used by ${olduser}, deleting..."; \
        userdel -r -f "${olduser}" || true; \
    fi; \
    if getent group "${GID}" >/dev/null; then \
        oldgroup=$(getent group "${GID}" | cut -d: -f1); \
        echo "GID ${GID} already used by ${oldgroup}, deleting..."; \
        groupdel "${oldgroup}" || true; \
    fi; \
    # 新規グループ・ユーザーを作成
    groupadd -g "${GID}" dev; \
    useradd -m -u "${UID}" -g "${GID}" -s /bin/bash dev; \
    # 念のためホーム権限を確認
    chown -R "${UID}:${GID}" /home/dev

USER dev
WORKDIR /workspace
.devcontainer/init_env.sh
#!/bin/bash
set -eu
SCRIPT_FILE="$(cd "$(dirname "$0")"; pwd)/$(basename "$0")"

cd $(dirname $SCRIPT_FILE)

rm -f .env
touch .env
echo "HOST_UID=$(id -u)" >> .env
echo "HOST_GID=$(id -g)" >> .env
.devcontainer/devcontainer.json
{
    "name": "<YOUR_PROJECT_NAME>",
    "dockerComposeFile": "compose.yaml",
    "service": "devel",
    "workspaceFolder": "/workspace",
    "customizations": {
        "vscode": {
            "extensions": [
                "ms-python.python",
                "charliermarsh.ruff"
            ],
            "settings": {
                "python.defaultInterpreterPath": "/workspace/.venv/bin/python",
                "[python]": {
                    "editor.codeActionsOnSave": {
                        "source.fixAll.ruff": "explicit",
                        "source.organizeImports.ruff": "explicit"
                    },
                    "editor.defaultFormatter": "charliermarsh.ruff",
                    "editor.formatOnSave": true,
                    "editor.formatOnType": true
                }
            }
        }
    },
    "initializeCommand": ".devcontainer/init_env.sh",
}

Discussion