docker_optimization
БесплатноБез исполняемых скриптовНе проверенDocker image optimization patterns including multi-stage builds, layer caching, security hardening, and size reduction techniques. Use when building Docker…
от vuralserhat86★ 43 звезды на GitHubОб этом скилле
Docker Optimization Patterns
Comprehensive guide to optimizing Docker images for size, build speed, and security. Covers multi-stage builds, layer caching strategies, security hardening, and production deployment patterns.
Quick Reference
When to use this skill:
- Building production Docker images
- Optimizing image size (reducing from 500MB+ to <100MB)
- Improving Docker build times
- Implementing Docker security best practices
- Debugging slow builds or large images
- Setting up Docker for microservices
Common triggers:
- "My Docker image is too large"
- "Docker builds take forever"
- "How do I optimize this Dockerfile"
- "Docker security best practices"
- "Multi-stage build pattern"
Part 1: Multi-Stage Builds
The Problem: Bloated Images
Typical single-stage Dockerfile (800MB+ image):
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
Problems:
- Includes build tools (gcc, make, etc.) - 300MB+
- Includes pip cache - 100MB+
- Includes source .git directory - 50MB+
- Includes test files and dev dependencies - 50MB+
- Total: 800MB+ for simple Python app
The Solution: Multi-Stage Pattern
Optimized multi-stage Dockerfile (120MB image):
# Stage 1: Builder
FROM python:3.11-slim AS builder
WORKDIR /app
# Install build dependencies in separate layer
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
&& rm -rf /var/lib/apt/lists/*
# Copy only requirements first (cache optimization)
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# Stage 2: Runtime
FROM python:3.11-slim
WORKDIR /app
# Copy only Python packages from builder
COPY --from=builder /root/.local /root/.local
# Copy only application code
COPY app.py .
COPY src/ ./src/
# Make sure scripts in .local are usable
ENV PATH=/root/.local/bin:$PATH
# Run as non-root user
RUN useradd -m appuser && chown -R appuser:appuser /app
USER appuser
CMD ["python", "app.py"]
Result: 800MB → 120MB (85% reduction)
Multi-Stage Pattern Breakdown
Stage 1: Builder (Throw away after build)
- Install build tools
- Compile dependencies
- Run tests (optional)
- Generate artifacts
Stage 2: Runtime (Final image)
- Minimal base image
- Copy only artifacts from builder
- No build tools
- No source files (only compiled/necessary files)
Part 2: Layer Caching Optimization
Understanding Docker Layer Caching
Each instruction creates a layer. Docker caches unchanged layers.
Bad Order (cache invalidated on every code change):
FROM python:3.11-slim
COPY . . # ❌ Copies everything
RUN pip install -r requirements.txt # ❌ Runs on every code change
Good Order (cache preserved):
FROM python:3.11-slim
COPY requirements.txt . # ✅ Only requirements
RUN pip install -r requirements.txt # ✅ Cached if requirements unchanged
COPY . . # ✅ Code changes don't invalidate pip cache
Layer Caching Best Practices
1. Order by change frequency (least to most):
# 1. System dependencies (rarely change)
RUN apt-get update && apt-get install -y curl
# 2. Language runtime (rarely changes)
FROM python:3.11-slim
# 3. Dependencies (change occasionally)
COPY requirements.txt .
RUN pip install -r requirements.txt
# 4. Application code (changes frequently)
COPY . .
2. Separate COPY operations:
# ❌ Bad: Invalidates cache on any file change
COPY . .
# ✅ Good: Cache preserved unless specific files change
COPY package.json package-lock.json ./
RUN npm ci
COPY src/ ./src/
COPY public/ ./public/
3. Use .dockerignore:
# .dockerignore
.git
.gitignore
node_modules
npm-debug.log
Dockerfile
.dockerignore
.env
.venv
__pycache__
*.pyc
tests/
docs/
Part 3: Image Size Optimization
Choose Minimal Base Images
Image Size Comparison:
python:3.11 → 1.01GB
python:3.11-slim → 130MB (87% smaller)
python:3.11-alpine → 50MB (95% smaller)
When to use each:
- Full image (
python:3.11): Never for production - Slim (
python:3.11-slim): Default choice, good compatibility - Alpine (
python:3.11-alpine): Smallest, but can have glibc issues
Multi-Stage Size Optimization
Node.js Example (900MB → 150MB):
# Builder stage
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Result: 900MB → 150MB (83% reduction)
Clean Up in Same Layer
❌ Bad (creates large intermediate layers):
RUN apt-get update
RUN apt-get install -y build-essential
RUN rm -rf /var/lib/apt/lists/*
✅ Good (single layer, no intermediate garbage):
RUN apt-get upda
Установить docker_optimization в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл docker_optimization?
Docker image optimization patterns including multi-stage builds, layer caching, security hardening, and size reduction techniques. Use when building Docker images, optimizing container size, improving build performance, or implementing Docker security best practices. Reduces image sizes by 70-90% and build times by 50-80%.
Как установить скилл docker_optimization?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл docker_optimization запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
ci-review
The scan that the plugin's GitHub Action runs.
от Anthropicazure-static-web-apps
Helps create, configure, and deploy Azure Static Web Apps using the SWA CLI. Use when deploying static sites to Azure, setting up SWA local development…
от GitHubai-ready
Make any repo AI-ready — analyzes your codebase and generates AGENTS.md, copilot-instructions.md, CI workflows, issue templates, and more. Mines your PR…
от GitHubaws-cdk-python-setup
Setup and initialization guide for developing AWS CDK (Cloud Development Kit) applications in Python. This skill enables users to configure environment…
от GitHub