MCP HubMCP Hub
스킬 목록으로 돌아가기

optimize-docker-build-cache

pjt222
업데이트됨 2 days ago
4 조회
17
2
17
GitHub에서 보기
메타design

정보

이 스킬은 Docker 빌드 시간을 단축하기 위해 레이어 캐싱, 멀티스테이지 빌드, BuildKit 기능을 활용한 최적화 기법을 제공합니다. R, Node.js, Python 프로젝트에서 반복적인 의존성 설치로 인해 개발 속도가 저하되는 경우에 적합합니다. 코드 변경 시 전체 재빌드가 발생하거나 CI/CD 파이프라인에서 Docker 빌드 병목 현상이 발생할 때 사용하세요.

빠른 설치

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/optimize-docker-build-cache

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Optimize Docker Build Cache

Cut Docker build times through effective layer caching and build optimization.

When Use

  • Docker builds slow due to repeated package installations
  • Rebuilds reinstall all deps on every code change
  • Image sizes unnecessarily large
  • CI/CD pipeline builds are bottleneck

Inputs

  • Required: Existing Dockerfile to optimize
  • Optional: Target build time improvement
  • Optional: Target image size reduction

Steps

Step 1: Order Layers by Change Frequency

Place least-changing layers first:

# 1. Base image (rarely changes)
FROM rocker/r-ver:4.5.0

# 2. System dependencies (change occasionally)
RUN apt-get update && apt-get install -y \
    libcurl4-openssl-dev \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/*

# 3. Dependency files only (change when deps change)
COPY renv.lock renv.lock
COPY renv/activate.R renv/activate.R
RUN R -e "renv::restore()"

# 4. Source code (changes frequently)
COPY . .

Key principle: Docker caches each layer. When layer changes, all subsequent layers rebuilt. Dependency installation should come before source code copy.

Got: Dockerfile layers ordered from least-changing (base image, system deps) to most-changing (source code), with dependency lockfiles copied before full source.

If fail: Builds still reinstall deps on every code change? Verify COPY . . comes after dependency installation RUN command, not before.

Step 2: Separate Dependency Installation from Code

Bad (rebuilds packages on every code change):

COPY . .
RUN R -e "renv::restore()"

Good (only rebuilds packages when lockfile changes):

COPY renv.lock renv.lock
RUN R -e "renv::restore()"
COPY . .

Same pattern for Node.js:

COPY package.json package-lock.json ./
RUN npm ci
COPY . .

Got: Dependency lockfile (renv.lock, package-lock.json, requirements.txt) copied and installed in separate layer before full source COPY . ..

If fail: Lockfile copy fails? Ensure file exists in build context, not excluded by .dockerignore.

Step 3: Use Multi-Stage Builds

Separate build dependencies from runtime:

# Build stage - includes dev tools
FROM rocker/r-ver:4.5.0 AS builder
RUN apt-get update && apt-get install -y \
    libcurl4-openssl-dev libssl-dev build-essential
COPY renv.lock .
RUN R -e "install.packages('renv'); renv::restore()"

# Runtime stage - minimal image
FROM rocker/r-ver:4.5.0
RUN apt-get update && apt-get install -y \
    libcurl4 libssl3 \
    && rm -rf /var/lib/apt/lists/*
COPY --from=builder /usr/local/lib/R/site-library /usr/local/lib/R/site-library
COPY . /app
WORKDIR /app
CMD ["Rscript", "main.R"]

Got: Dockerfile has builder stage with dev tools and runtime stage with only production deps. Final image significantly smaller than single-stage build.

If fail: COPY --from=builder fails to find libraries? Verify install path matches between stages. Use docker build --target builder . to debug build stage independently.

Step 4: Combine RUN Commands

Each RUN creates layer. Combine related commands:

Bad (3 layers, apt cache persists):

RUN apt-get update
RUN apt-get install -y curl git
RUN rm -rf /var/lib/apt/lists/*

Good (1 layer, clean cache):

RUN apt-get update && apt-get install -y \
    curl \
    git \
    && rm -rf /var/lib/apt/lists/*

Got: Related apt-get or package install commands combined into single RUN instructions, each ending with cache cleanup (rm -rf /var/lib/apt/lists/*).

If fail: Combined RUN fails midway? Temporarily split to identify failing command, recombine after fixing.

Step 5: Use .dockerignore

Prevent unnecessary files from entering build context:

.git
.Rproj.user
.Rhistory
.RData
renv/library
renv/cache
node_modules
docs/
*.tar.gz
.env

Got: .dockerignore exists in project root excluding .git, node_modules, renv/library, build artifacts, environment files. Build context size noticeably smaller.

If fail: Needed files missing in container? Check .dockerignore for overly broad patterns. Use docker build verbose output to verify which files sent to daemon.

Step 6: Enable BuildKit

DOCKER_BUILDKIT=1 docker build -t myimage .

Or in docker-compose.yml:

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile

With COMPOSE_DOCKER_CLI_BUILD=1 and DOCKER_BUILDKIT=1 environment variables.

BuildKit enables:

  • Parallel stage builds
  • Better cache management
  • --mount=type=cache for persistent package caches

Got: Builds run with BuildKit enabled (indicated by #1 [internal] load build definition style output). Multi-stage builds execute stages in parallel where possible.

If fail: BuildKit not active? Verify env vars exported before build command. On older Docker versions, upgrade Docker Engine to 18.09+ for BuildKit support.

Step 7: Use Cache Mounts for Package Managers

# R packages with persistent cache
RUN --mount=type=cache,target=/usr/local/lib/R/site-library \
    R -e "install.packages('dplyr')"

# npm with persistent cache
RUN --mount=type=cache,target=/root/.npm \
    npm ci

Got: Subsequent builds reuse cached packages from mount, dramatically reducing install times even when layer invalidated. Cache persists across builds.

If fail: --mount=type=cache not recognized? Ensure BuildKit enabled (DOCKER_BUILDKIT=1). Syntax requires BuildKit, not supported by legacy builder.

Checks

  • Rebuilds after code-only changes significantly faster
  • Dependency installation layer cached when lockfile unchanged
  • .dockerignore excludes unnecessary files
  • Image size reduced compared to unoptimized build
  • Multi-stage build (if used) separates build and runtime deps

Pitfalls

  • Copying all files before installing deps: Invalidates dependency cache on every code change
  • Forgetting .dockerignore: Large build contexts slow every build
  • Too many layers: Each RUN, COPY, ADD creates layer. Combine where logical.
  • Not cleaning apt cache: Always end apt-get installs with && rm -rf /var/lib/apt/lists/*
  • Platform-specific caches: Cache layers platform-specific. CI runners may not benefit from local caches.

See Also

  • create-r-dockerfile - initial Dockerfile creation
  • setup-docker-compose - compose build configuration
  • containerize-mcp-server - apply optimizations to MCP server builds

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman/skills/optimize-docker-build-cache
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기