スキル一覧に戻る

create-multistage-dockerfile

pjt222
更新日 Yesterday
2 閲覧
17
2
17
GitHubで表示
メタaidesign

について

このClaudeスキルは、ビルド環境とランタイム環境を分離した最適化された多段階Dockerfileを生成し、最小限の本番用イメージを作成します。イメージが大きすぎる場合、不要なビルドツールが含まれている場合、エッジコンピューティングのような制約のある環境へのデプロイが必要な場合に役立ちます。このスキルは、ビルダー/ランタイムステージの分離、アーティファクトのコピー、scratch、distroless、Alpineベースなどのターゲットをカバーしています。

クイックインストール

Claude Code

推奨
メイン
npx skills add pjt222/agent-almanac -a claude-code
プラグインコマンド代替
/plugin add https://github.com/pjt222/agent-almanac
Git クローン代替
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/create-multistage-dockerfile

このコマンドをClaude Codeにコピー&ペーストしてスキルをインストールします

ドキュメント

Create Multi-Stage Dockerfile

Build multi-stage Dockerfiles that produce minimal production images by separating build tooling from runtime.

When to Use

  • Production images are too large (>500MB for compiled languages)
  • Build tools (compilers, dev headers) are included in the final image
  • Need separate images for development and production from one Dockerfile
  • Deploying to constrained environments (edge, serverless)

Inputs

  • Required: Existing Dockerfile or project to containerize
  • Required: Language and build system (npm, pip, go build, cargo, maven)
  • Optional: Target runtime base (slim, alpine, distroless, scratch)
  • Optional: Size budget for final image

Procedure

Step 1: Identify Build vs Runtime Dependencies

CategoryBuild StageRuntime Stage
Compilersgcc, g++, rustcNot needed
Package managersnpm, pip, cargoSometimes (interpreted langs)
Dev headers-dev packagesNot needed
Source codeFull source treeOnly compiled output
Test frameworksjest, pytestNot needed

Step 2: Structure the Multi-Stage Build

The core pattern: build in a fat image, copy artifacts to a slim image.

# ---- Build Stage ----
FROM <build-image> AS builder
WORKDIR /src
COPY <dependency-manifest> .
RUN <install-dependencies>
COPY . .
RUN <build-command>

# ---- Runtime Stage ----
FROM <runtime-image>
COPY --from=builder /src/<artifact> /<dest>
EXPOSE <port>
CMD [<entrypoint>]

Step 3: Apply Language-Specific Patterns

Node.js (pruned node_modules)

FROM node:22-bookworm AS builder
WORKDIR /src
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:22-bookworm-slim
RUN groupadd -r app && useradd -r -g app app
WORKDIR /app
COPY --from=builder /src/dist ./dist
COPY --from=builder /src/node_modules ./node_modules
COPY --from=builder /src/package.json .
USER app
EXPOSE 3000
CMD ["node", "dist/index.js"]

Python (virtualenv copy)

FROM python:3.12-bookworm AS builder
WORKDIR /src
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

FROM python:3.12-slim-bookworm
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /app
COPY --from=builder /src .
RUN groupadd -r app && useradd -r -g app app
USER app
EXPOSE 8000
CMD ["python", "app.py"]

Go (static binary to scratch)

FROM golang:1.23-bookworm AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server

FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /server /server
EXPOSE 8080
ENTRYPOINT ["/server"]

Rust (static musl binary)

FROM rust:1.82-bookworm AS builder
RUN apt-get update && apt-get install -y musl-tools && rm -rf /var/lib/apt/lists/*
RUN rustup target add x86_64-unknown-linux-musl
WORKDIR /src
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {}" > src/main.rs \
    && cargo build --release --target x86_64-unknown-linux-musl \
    && rm -rf src
COPY . .
RUN touch src/main.rs && cargo build --release --target x86_64-unknown-linux-musl

FROM scratch
COPY --from=builder /src/target/x86_64-unknown-linux-musl/release/myapp /myapp
EXPOSE 8080
ENTRYPOINT ["/myapp"]

Got: Final image contains only the runtime and compiled artifacts.

If fail: Check COPY --from=builder paths. Use docker build --target builder to debug the build stage.

Step 4: Choose Runtime Base

BaseSizeShellUse Case
scratch0 MBNoStatic Go/Rust binaries
gcr.io/distroless/static~2 MBNoStatic binaries + CA certs
gcr.io/distroless/base~20 MBNoDynamic binaries (libc)
*-slim50-150 MBYesInterpreted languages
alpine~7 MBYesWhen shell access needed

Note: Alpine uses musl libc. Some Python wheels and Node native modules may not work. Prefer -slim (glibc) for interpreted languages.

Step 5: Build Args Across Stages

ARG APP_VERSION=0.0.0

FROM golang:1.23 AS builder
ARG APP_VERSION
RUN go build -ldflags="-X main.version=${APP_VERSION}" -o /server .

FROM gcr.io/distroless/static
COPY --from=builder /server /server
ENTRYPOINT ["/server"]

Build with: docker build --build-arg APP_VERSION=1.2.3 .

Note: ARG before FROM is global. Each stage must re-declare ARG to use it.

Step 6: Compare Image Sizes

# Build both variants
docker build -t myapp:fat --target builder .
docker build -t myapp:slim .

# Compare sizes
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" | grep myapp

Got: Production image is 50-90% smaller than the build stage.

Validation

  • docker build completes for all stages
  • Final image does not contain build tools (compilers, dev headers)
  • docker run works correctly from the slim image
  • Image size is significantly reduced vs single-stage
  • COPY --from=builder paths are correct
  • No source code leaks into the production image

Pitfalls

  • Missing runtime libraries: Compiled code may need shared libraries (libc, libssl). Test the slim image thoroughly.
  • Broken COPY --from paths: The artifact path must match exactly. Use docker build --target builder then docker run --rm builder ls /path to debug.
  • Alpine musl issues: Native Node.js addons and some Python packages fail on Alpine. Use -slim instead.
  • Global ARG scope: An ARG declared before FROM is available to FROM lines only. Re-declare inside each stage that needs it.
  • Forgetting CA certificates: scratch has no certificates. Copy /etc/ssl/certs/ca-certificates.crt from the builder or use distroless.

Related Skills

  • create-dockerfile - single-stage general Dockerfiles
  • create-r-dockerfile - R-specific Dockerfiles with rocker images
  • optimize-docker-build-cache - layer caching and BuildKit features
  • setup-compose-stack - compose configurations using multi-stage images

GitHub リポジトリ

pjt222/agent-almanac
パス: i18n/caveman-lite/skills/create-multistage-dockerfile
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

関連スキル

content-collections

メタ

このスキルは、Content Collections(Markdown/MDXファイルを型安全なデータコレクションに変換するTypeScriptファーストのツール)の本番環境でテストされた設定を提供します。Zodバリデーションによる型安全性を実現し、ブログ、ドキュメントサイト、コンテンツ重視のVite + Reactアプリケーション構築時にご利用ください。Viteプラグインの設定、MDXコンパイルから、デプロイ最適化、スキーマバリデーションまで、すべてを網羅しています。

スキルを見る

polymarket

メタ

このスキルは、開発者がPolymarket予測市場プラットフォームを活用したアプリケーション構築を可能にします。API統合による取引や市場データの取得に加え、WebSocketを介したリアルタイムデータストリーミングにより、ライブ取引や市場活動を監視できます。取引戦略の実装や、ライブ市場更新を処理するツールの作成にご利用ください。

スキルを見る

creating-opencode-plugins

メタ

このスキルは、開発者がコマンド、ファイル、LSP操作など25種類以上のイベントタイプにフックするOpenCodeプラグインを作成することを支援します。JavaScript/TypeScriptモジュール向けに、プラグイン構造、イベントAPI仕様、および実装パターンを提供します。カスタムイベント駆動ロジックでOpenCode AIアシスタントのライフサイクルをインターセプト、監視、または拡張する必要がある場合にご利用ください。

スキルを見る

sglang

メタ

SGLangは、高性能なLLMサービングフレームワークであり、RadixAttentionプレフィックスキャッシュを活用したJSON、正規表現、エージェントワークフロー向けの高速で構造化された生成を特長とします。特にプレフィックスが繰り返されるタスクにおいて、大幅に高速な推論を実現し、複雑な構造化出力やマルチターン対話に最適です。制約付きデコードが必要な場合や、広範なプレフィックス共有を伴うアプリケーションを構築する場合は、vLLMなどの代替案ではなくSGLangを選択してください。

スキルを見る